1. 程式人生 > >15、劍指offer--反轉鏈表

15、劍指offer--反轉鏈表

log truct png offer all 輸出 需要 while node

題目描述 輸入一個鏈表,反轉鏈表後,輸出鏈表的所有元素。 解題思路:該題需要定義三個指針,分別記錄當前結點、前一結點、下一結點。 反轉過程中,先獲得下一結點,然後讓當前結點下一個指向前一結點,下一個前一結點為當前結點,當前結點為下一結點。註意如果下一結點為空,則當前結點為為最後一個結點,即返回的頭指針。
 1 #include <iostream>
 2 #include <malloc.h>
 3 using namespace std;
 4 struct ListNode {
 5     int val;
 6     struct ListNode *next;
7 ListNode(int x) : 8 val(x), next(NULL) { 9 } 10 }; 11 class Solution { 12 public: 13 //需要定義三個指針、當前節點、前一個節點、後一個節點 14 ListNode* ReverseList(ListNode* pHead) { 15 ListNode *pre = NULL; 16 ListNode *pNode = pHead; 17 ListNode *pReverseHead = pHead; 18
while(pNode != NULL) 19 { 20 ListNode *pNext = pNode->next;//保存下一結點 21 if(pNext == NULL)//下一結點為空 22 { 23 pReverseHead = pNode;//當前結點為最後一個結點,即為返回的頭指針 24 } 25 pNode->next = pre;//當前結點下一個指向前一個結點 26 pre = pNode;//
前一結點為當前結點 27 pNode = pNext;//當前結點後移 28 29 } 30 return pReverseHead; 31 } 32 }; 33 ListNode *CreateList(int n) 34 { 35 ListNode *head; 36 ListNode *p,*pre; 37 int i; 38 head=(ListNode *)malloc(sizeof(ListNode)); 39 head->next=NULL; 40 pre=head; 41 for(i=1;i<=n;i++) 42 { 43 p=(ListNode *)malloc(sizeof(ListNode)); 44 cin>>p->val; 45 pre->next=p; 46 pre=p; 47 } 48 p->next=NULL; 49 50 return head->next; 51 } 52 /*-------------------------輸出鏈表-----------------------------------*/ 53 void PrintList(ListNode *h) 54 { 55 ListNode *p; 56 57 p=h;//不帶空的頭結點 58 while(p) 59 { 60 cout<<p->val<<" "; 61 p=p->next; 62 cout<<endl; 63 } 64 } 65 int main() 66 { 67 int n1; 68 ListNode *h1; 69 cout<<"輸入鏈表的結點數目"<<endl; 70 cin>>n1; 71 h1 = CreateList(n1); 72 cout<<"鏈表為:"<<endl; 73 PrintList(h1); 74 cout<<"反轉後鏈表為:"<<endl; 75 Solution s; 76 h1 = s.ReverseList(h1); 77 PrintList(h1); 78 return 0; 79 }

技術分享

15、劍指offer--反轉鏈表