題目:
輸入一個鏈表,反轉鏈表后,輸出鏈表的所有元素。
思路:
反轉鏈表,對于片段 1--->2--->3循環操作; 要反轉鏈表需要兩步:
一,將2->next指向1 (如果不保存3那么此時就丟失了對3的引用)
二,將鏈表往后移 即 : 1=2; 2=3;3=3->next
注意的點:
一,首節點的next要指向NULL
二:鏈表的長度可能小于3
代碼:
/*
struct ListNode {int val;struct ListNode *next;ListNode(int x) :val(x), next(NULL) {}
};*/
class Solution {
public:ListNode* ReverseList(ListNode* pHead) {if(pHead==NULL) return NULL;ListNode* newHead;ListNode* p1=pHead;ListNode* p2=pHead->next;ListNode* p3; if(p2!=NULL){p3=p2->next;p1->next=NULL;p2->next=p1;while(p3!=NULL){p1=p2;p2=p3;p3=p3->next;p2->next=p1;}newHead=p2;}else{p1->next=NULL;newHead=p1;}return newHead;}
};