本例使用“表尾插入法”创建一个链表,而用“表头插入”的思想对链表就地逆置。
#include<stdio.h>
#include<stdlib.h>
typedef struct Node {
int value;
Node *next;
}ListNode, *List;
#define LISTLEN sizeof(ListNode)
List createList(int values[], int length) {
List head, precious, p;
head=(List)malloc(LISTLEN);
head->next=NULL;
precious=head;
for(int i=0; i<length; i++) {
p=(List)malloc(LISTLEN);
p->value=values[i];
p->next=NULL;
precious->next=p;
precious=p;
}
return head;
}
void traverseList(List list) {
List p=list->next;
while(p!=NULL) {
printf("%d\n", p->value);
p=p->next;
}
}
void inverseList(List list) {
if(list->next==NULL) { return; }
List head=list, chain=list->next, p;
head->next=NULL;
while(chain!=NULL) {
p=chain;
chain=chain->next;
p->next=head->next;
head->next=p;
}
}
int main(void) {
int values[]={1,2,3,4,5,6}, length=6;
List list=createList(values, length);
traverseList(list);
inverseList(list);
traverseList(list);
return 0;
}