leetcode 92 反轉鍊錶 II

2021-10-03 11:41:10 字數 1789 閱讀 4208

反轉鍊錶 ii

反轉從位置 m 到 n 的鍊錶。請使用一趟掃瞄完成反轉。

說明:1 ≤ m ≤ n ≤ 鍊錶長度。

示例:輸入: 1->2->3->4->5->null, m = 2, n = 4

輸出: 1->4->3->2->5->null

補充:c語言版本

/**

* definition for singly-linked list.

* struct listnode ;

*/struct listnode*

reversebetween

(struct listnode* head,

int m,

int n)

struct listnode* pre =

null

;struct listnode* cur = head;

while

(m >1)

struct listnode* start = pre;

struct listnode* tail = cur;

while

(n >0)

if(null

== start)

else

tail->next = cur;

return head;

}/*0ms,5.4mb*/

思路一:遞迴法

/**

* definition for singly-linked list.

* struct listnode

* };

*/class

solution

if(m ==1)

head-

>next =

reversebetween

(head-

>next, m -

1, n -1)

;return head;

} listnode*

reversen

(listnode* head,

int n)

if(n ==1)

listnode* last =

reversen

(head-

>next, n -1)

; head-

>next-

>next = head;

head-

>next = successor;

return last;}}

;/*0ms,9.9mb*/

時間複雜度: o(n)

空間複雜度: o(n)

思路二:迭代法

class

solution

listnode* pre =

null

; listnode* cur = head;

while

(m >1)

listnode* pstart = pre;

listnode* tail = cur;

while

(n >0)

if(null

!= pstart)

else

tail-

>next = cur;

return head;}}

;/*0ms,9.8mb*/

時間複雜度: o(n)

空間複雜度: o(1)

leetcode 92反轉鍊錶

反轉從位置 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.public class listnode class...

LeetCode 92 反轉鍊錶 II

反轉從位置 m 到 n 的鍊錶。請使用一趟掃瞄完成反轉。說明 1 m n 鍊錶長度。示例 輸入 1 2 3 4 5 null,m 2,n 4 輸出 1 4 3 2 5 null 5ms definition for singly linked list.public class listnode c...

leetcode92 反轉鍊錶 II

反轉從位置 m 到 n 的鍊錶。請使用一趟掃瞄完成反轉。說明 1 m n 鍊錶長度。示例 輸入 1 2 3 4 5 null,m 2,n 4輸出 1 4 3 2 5 null思路 先往後遍歷找到需要反轉的節點作為起點 count m 然後按照劍指offer 反轉鍊錶 的思路,設定curr,pre,p...