Reverse Linked List
Reverse a singly linked list.
click to show more hints.
Hint:A linked list can be reversed either iteratively or recursively. Could you implement both?
|prev |cur |next
v v v
--- --- --- ---
NULL | |-->| |-->| |-->...-->| |-->NULL
--- --- --- ---
I
3 5
2|prev |cur |next
v v v
--- --- --- ---
NULL<--| |<--| | | |-->...-->| |-->NULL
1 --- 4 --- --- ---
主要是頭結(jié)點(diǎn)平移時(shí)候注意cur->next是怎么連接的。
pre->next=head->next;而不是cur->next;
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:ListNode* reverseList(ListNode* head) {//因?yàn)楣?jié)點(diǎn)頭有數(shù)據(jù) 創(chuàng)建一個(gè)空的頭結(jié)點(diǎn)if(!head) return head;ListNode* temp=new ListNode(NULL);temp->next=head;ListNode* cur=head;while(cur->next){ListNode* pre=cur->next;cur->next=pre->next;pre->next=temp->next;//最主要的一步 怎么倒置連接temp->next=pre;}return temp->next;} };
遞歸解法的思路是,不斷的進(jìn)入遞歸函數(shù),直到head指向最后一個(gè)節(jié)點(diǎn),p指向之前一個(gè)節(jié)點(diǎn),然后調(diào)換head和p的位置,再返回上一層遞歸函數(shù),再交換p和head的位置,每次交換后,head節(jié)點(diǎn)后面都是交換好的順序,直到p為首節(jié)點(diǎn),然后再交換,首節(jié)點(diǎn)就成了為節(jié)點(diǎn),此時(shí)整個(gè)鏈表也完成了翻轉(zhuǎn)
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:ListNode* reverseList(ListNode* head) {if(!head || !head->next) return head;ListNode *p = head;head = reverseList(p->next);p->next->next = p;p->next = NULL;return head;} };
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:ListNode* reverseList(ListNode* head) {if(head==NULL || head->next==NULL) return head;ListNode* p=head;ListNode* cur=head->next;p->next=NULL;while(cur!=NULL){ListNode* temp=cur->next;cur->next=p;p=cur;cur=temp;}return p;} };
總結(jié)
以上是生活随笔為你收集整理的Reverse Linked List的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Python标准库04 文件管理 (部分
- 下一篇: LLC算法coding与pooling解