Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given
Given
1->2->3->4->5->NULL, m = 2 and n = 4,
return
Solution:
1->2->3->4->5->NULL
1->3->2->4->5->NULL
1->4->3->2->5->NULL always insert the element after the (m-1)th element.
1->4->3->2->5->NULL.Solution:
1->2->3->4->5->NULL
1->3->2->4->5->NULL
1->4->3->2->5->NULL always insert the element after the (m-1)th element.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
/**
* 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 dummy = new ListNode(0);
dummy.next = head;
ListNode cur = head;
ListNode pre = dummy;
int pos = 1;
while(pos < m && cur != null){
pre = cur;
cur = cur.next;
pos++;
}
while(pos < n && cur != null){
ListNode nt = cur.next.next;
cur.next.next = pre.next;
pre.next = cur.next;
cur.next = nt;
pos++;
}
return dummy.next;
}
}
No comments:
Post a Comment