連結串列的逆置(C版)
阿新 • • 發佈:2018-12-18
#include<stdio.h> #include<stdlib.h> #define OK 1 #define ERROR -1 #define MAX_SIZE 100 typedef int Status; typedef char ElemType; typedef struct LinkList { ElemType data[MAX_SIZE]; int length; }LinkList; void DipList(LinkList *L) { int i; for(i = 0;i<L->length;i++) { printf("%c\n",L->data[i]); } } Status ListInsert(LinkList *L,int i,ElemType e) { int j; if (i<1 || i>L->length+1) return ERROR; i--; //將順序表位序轉化為elem下標 for (j=L->length;j>i;j--) //將data[i]及後面元素後移一個位置 L->data[i]=L->data[i-1]; L->data[i]=e; L->length++; //順序表長度增1 return OK; } Status ReverseList(LinkList *L) { int i; ElemType temp; if(L->length==0) { printf("表為空!\n"); return ERROR; } else { for(i = 0;i<L->length/2;i++) { temp = L->data[i]; L->data[i] = L->data[L->length-i-1]; L->data[L->length-i-1]=temp; } } } int main() { LinkList L; L.length =0; ListInsert(&L,1,'a'); ListInsert(&L,2,'b'); ListInsert(&L,3,'c'); ListInsert(&L,4,'d'); ListInsert(&L,5,'e'); ListInsert(&L,6,'f'); printf("線性表的值如下:\n"); DipList(&L); printf("線性表逆置之後的值如下:\n"); ReverseList(&L); DipList(&L); }