DS

线性表的逆置(反转)

convert list

Posted by xuepro on November 9, 2017

原理请观看数据结构视频课程的“网易云课堂”“腾讯课堂”

——链式表的逆置————

#include <stdio.h>
#include <stdlib.h>

#define ERROR 1
#define OK 0

typedef char EType;

typedef struct lnode{
    EType data;
    struct lnode *next;
}LNode;


LNode *newLNode(){
   LNode *p = (LNode *)malloc(sizeof(LNode));
   if(!p) return 0;
   p->next = 0;
   return p;
}

LNode *initLkList(){
   return newLNode();
}

int insert_front_LkList(LNode *L,EType e){
    LNode *p = newLNode(); if(!p) return ERROR;
    p->data = e;
    p->next = L->next;
    L->next = p;
    return OK;
}

void converse_LkList(LNode *L){
   LNode *p,*q;
   p = L->next;
   L->next = 0;
   while(p){ /*前插法到头结点后面*/
     q = p->next; /*保存下一个结点地址*/
     p->next = L->next; /*指向新链表首结点*/
     L->next = p;
     p = q;
   }
}

void printLkList(LNode *L){
   LNode *p = L->next;
   while(p){
      printf("%c\t",p->data);
      p = p->next;
   }
   printf("\n");
}

int main(){
    LNode *L;
    L = initLkList();
    insert_front_LkList(L,'A');
    insert_front_LkList(L,'B');
    insert_front_LkList(L,'C');
    insert_front_LkList(L,'D');
    printLkList(L);
    converse_LkList(L);
    printLkList(L);

}

——顺序表的逆置————

#include <stdio.h>

typedef char T;
void converse(T a[],int n){
    int i=0,j=n-1;
    while(i<j){
        T t = a[i]; a[i] = a[j]; a[j] = t;
        i++; j--;
    }
}
int main(){
    char arr[] = {'A','B','C','D'};
    converse(arr,4);
    for(int i = 0 ; i<4;i++)
        printf("%c ",arr[i]);
    printf("\n");
}

支付宝打赏 微信打赏

您的打赏是对我最大的鼓励!