Reverse Linked List
生活随笔
收集整理的這篇文章主要介紹了
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 --- --- ---
主要是頭結點平移時候注意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) {//因為節點頭有數據 創建一個空的頭結點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;} };
遞歸解法的思路是,不斷的進入遞歸函數,直到head指向最后一個節點,p指向之前一個節點,然后調換head和p的位置,再返回上一層遞歸函數,再交換p和head的位置,每次交換后,head節點后面都是交換好的順序,直到p為首節點,然后再交換,首節點就成了為節點,此時整個鏈表也完成了翻轉
/*** 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;} };
總結
以上是生活随笔為你收集整理的Reverse Linked List的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python标准库04 文件管理 (部分
- 下一篇: LLC算法coding与pooling解