日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

Reverse Linked List

發(fā)布時(shí)間:2025/4/16 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Reverse Linked List 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。