循环法:
#include "linklist.cpp" #include#include LinkNode *func(LinkNode *L) { LinkNode *pre,*current,*temp;//current新建的头节点,pre旧节点,temp临时节点 current=L->next; //因为从main函数传过来的L指针前面有个空的头节点,所以使用的时候需要让让他指向下一个含有数据的节点 pre=NULL; //因为要倒置链表,所以最后一个她是指向NULl,所以这里需要先让pre指向NULL while(current!=NULL) //进入循环,因为current已经指向了L这个结构体指针,所以L所具有的后续的链表current也是有的 { temp=current->next;//先让temp指向下一个节点 current->next=pre;//current的下一个指向pre,也就是NULL pre=current;//pre现在就可以指向current了,这就完成了链表从头开始倒着指向前一个节点 current=temp; //current就可以指向下一个了,然后一直重复这个循环,就可以完成链表从头开始指向前一个节点 } temp=(LinkNode *)malloc(sizeof(LinkNode)); //利用temp创建一个新的空的头节点 L=temp; //让L指向这个空节点 L->next=pre; //让L的后面接上刚刚循环完成的链表倒置 return L; //最后返回L头节点 } void Display(LinkNode *L){ LinkNode *p=L->next; while(p){ printf("%c ",p->data); p=p->next; } } int main() { LinkNode *L,*l; char a[]="12345678"; int n=8; CreateListR(L,a,n); printf("L:"); DispList(L); printf("逆置Ln"); l=func(L); printf("L:"); Display(l); DestroyList(L); return 1; }
头插法:
#include "linklist.cpp" #include#include LinkNode *func(LinkNode *L){ LNode *front,*temp; front=(LinkNode *)malloc(sizeof(LinkNode)); front->next=NULL; L=L->next; while(L){ temp=L; L=L->next; temp->next=front->next; front->next=temp; } return front; } void Display(LinkNode *L){ LinkNode *p=L->next; while(p){ printf("%c ",p->data); p=p->next; } } int main() { LinkNode *L,*l; char a[]="12345678"; int n=8; CreateListR(L,a,n); printf("L:"); DispList(L); printf("逆置Ln"); l=func(L); printf("L:"); Display(l); DestroyList(L); return 1; }



