实现单链表逆置
?
?
看到筆試和面試里很多這樣的題目,于是就練習一下,溫故知新。
#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;elsecout<<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;elsebreak; }// 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; }
截圖:
總結
- 上一篇: Attribute的一个列子
- 下一篇: apk反编译看包名什么的