Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given
1->2->3->4->5->NULL
, m = 2 and n = 4,
return
1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
Naive Way:一开始想了一个不断交换的方法,这样可以做到in-place,但是交换之后最大的麻烦就是无法在O(1)的时间找回远端的节点的父节点,所以这个方法不符合O(n)的复杂度。然后才想到了这个不断插入的做法。现将远端的指针和近端指针摆好,不断将近端指针指向的插入远端指针后面,直到近端指向远端指针。也可以不断将近端后面的指针插入近端前面,知道近端和远端相遇。
算法复杂度是O(n), space O(1)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode newHead = new ListNode(0);
newHead.next = head;
ListNode p1 = newHead, p2 = p1;
int i = 0;
while(++i <= n && p2.next!=null){
if(i < m) p1 = p1.next;
p2 = p2.next;
}
// since n <= length of list, no need to check i<n
while(p1.next!=p2){
ListNode temp = p1.next;
p1.next = temp.next;
temp.next = p2.next;
p2.next = temp;
}
return newHead.next;
}
}
No comments:
Post a Comment