Leetcode
反轉從位置 m 到 n 的鏈表。請使用一趟掃描完成反轉。
說明:
1 ≤ m ≤ n ≤ 鏈表長度。
示例:
輸入: 1->2->3->4->5->NULL, m = 2, n = 4
輸出: 1->4->3->2->5->NULL
自己用迭代的方式寫了一次,思路簡單,在紙上把圖畫明白就會了。 記錄一下遞歸方式,遞歸要我命!好難!
代碼學習了題解某大佬的方法。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* N = NULL; //保存返回節點的下一個值
/*反轉鏈表的前n個節點*/
struct ListNode* Re(struct ListNode* head, int n){
if(n == 1) {
N = head->next;
return head;
}
struct ListNode* last = Re(head->next, n-1);
head->next->next = head;
head->next = N;
return last;
}
struct ListNode* reverseBetween(struct ListNode* head, int m, int n){
if(m == 1){
return Re(head, n); //返回翻轉後的頭節點
}
head->next = reverseBetween(head->next, m-1, n-1);
return head;
}