日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Reverse Linked List

發布時間:2025/4/16 编程问答 14 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。