实现单链表逆置
看到笔试和面试里很多这样的题目,于是就练习一下,温故知新。
#include <iostream> #include <cstdlib> using namespace std; typedef struct List { int data; struct List *next; }listNode,*pList; void createList(pList & list) //头插入法建立单链表 { pList head=NULL; int data; cout<<"please input a node:"; cin>>data; list=(struct List *)malloc(sizeof(listNode)); list->data=data; list->next=head; head=list; while(data!=9) { cout<<"please input a node:"; cin>>data; list=(struct List*)malloc(sizeof(listNode)); list->data=data; list->next=head; head=list; } } void display(pList list) //输出单链表 { pList temp; temp=list; while(temp!=NULL) { if(temp->next==NULL) cout<<temp->data; else cout<<temp->data<<"->"; temp=temp->next; } cout<<endl; } void reverseList(pList& list) //逆置单链表 { pList pre; pList temp; pre=list->next; //记录当前节点 temp=pre->next; //记录下一个节点 list->next=NULL; while(pre!=NULL) { pre->next=list; list=pre; pre=temp; if(pre!=NULL) temp=temp->next; else break; } // pre->next=list; // list=pre; } int main() { pList list=NULL; cout<<"create the list :"<<endl; createList(list); cout<<"output the list:"<<endl; display(list); cout<<endl; cout<<"reverse the List:"<<endl; reverseList(list); cout<<"output the reverse list:"<<endl; display(list); cout<<endl; return 0; }
上面逆置算法也可以这样写:
void reverseList(pList& list) //逆置 { pList pre; pList temp; pre=list->next; //记录当前节点 temp=pre->next; //记录下一个节点 list->next=NULL; while(temp!=NULL) { pre->next=list; list=pre; pre=temp; temp=temp->next; } pre->next=list; list=pre; }
截图: