LeetCode Reverse Linked List II 反置链表2
生活随笔
收集整理的這篇文章主要介紹了
LeetCode Reverse Linked List II 反置链表2
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
?
題意:將指定的一段位置[m,n]的鏈表反置,返回鏈表頭。
思路:主要麻煩在鏈表頭,如果要從鏈表頭就開始,比較特殊。
目前用DFS實現,先找到m-1的位置,再找到n+1的位置,中間這段就是否要反置的,交給DFS解決,用個計數器來統計已經反置的個數即可。
?
?
?
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* DFS(ListNode* t,ListNode* far, int num) 12 { 13 if(num==0) return far; 14 ListNode* tmp=t->next; 15 t->next=far; 16 return DFS(tmp , t, num-1); 17 } 18 19 ListNode* reverseBetween(ListNode* head, int m, int n) { 20 if(m==n) return head; 21 ListNode* t=head, *r=head; 22 23 for(int i=0; i<n; i++) r=r->next; //找到第n+1個 24 if(m==1) return DFS(head, r, n-m+1); 25 26 for(int i=1; i<m-1; i++) t=t->next; //找到第m-1個 27 t->next=DFS(t->next, r, n-m+1); 28 return head; 29 } 30 }; AC代碼?
轉載于:https://www.cnblogs.com/xcw0754/p/4685426.html
總結
以上是生活随笔為你收集整理的LeetCode Reverse Linked List II 反置链表2的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 鸿雁电器oa系统中决策支持模块效果
- 下一篇: 用到的 git 命令