Skip to content

Instantly share code, notes, and snippets.

@wszdwp
Created November 8, 2014 17:55
Show Gist options
  • Select an option

  • Save wszdwp/0546d7621627b07ad39c to your computer and use it in GitHub Desktop.

Select an option

Save wszdwp/0546d7621627b07ad39c to your computer and use it in GitHub Desktop.
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.
/**
* 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) {
if (head == null || head.next == null)
return head;
if (m >= n || m < 0 || n < 0)
return head;
ListNode fakeHead = new ListNode(0);
fakeHead.next = head;
ListNode p1 = fakeHead;
ListNode hd = p1;
ListNode tl = p1;
int count = 0;
while (p1 != null) {
if (count+1 == m) {
hd = p1;
}
if (count == n) {
tl = p1.next;
break;
}
count++;
p1 = p1.next;
}
hd = reverseList(hd, tl);
return fakeHead.next;
}
//reverse the list between head and tail, not include head and tail
public ListNode reverseList(ListNode head, ListNode tail) {
ListNode curr = head.next;
ListNode prev = tail;
while (curr != tail) {
ListNode temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
head.next = prev;
return head;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment