everse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->6->7->8->9->NULL, m = 2, n = 4
Output: 1->2->7->6->5->4->3->8->9->NULL
题解:
经典的题目就是链表逆序啦,一般的链表逆序是让把链表从前到后都逆序,这个是给定了起始位置和结束位置,方法是一样的。
就是维护3个指针,startpoint,node1和node2。
startpoint永远指向需要开始reverse的点的前一个位置。
node1指向正序中第一个需要rever的node,node2指向正序中第二个需要reverse的node。
交换后,node1 在后,node2在前。这样整个链表就逆序好了。
代码:
public class ReverseLinkedListII
{
public static void main(String[] args)
{
/**
* Reverse a linked list from position m to n. Do it in one-pass.
*
* Note: 1 ≤ m ≤ n ≤ length of list.
*
* Example:
*
* Input: 1->2->3->4->5->NULL, m = 2, n = 4
* Output: 1->4->3->2->5->NULL
*/
ListNode ln1 = new ListNode(1);
ListNode ln2 = new ListNode(2);
ListNode ln3 = new ListNode(3);
ListNode ln4 = new ListNode(4);
ListNode ln5 = new ListNode(5);
ListNode ln6 = new ListNode(6);
ListNode ln7 = new ListNode(7);
ListNode ln8 = new ListNode(8);
ListNode ln9 = new ListNode(9);
ln1.next = ln2;
ln2.next = ln3;
ln3.next = ln4;
ln4.next = ln5;
ln5.next = ln6;
ln6.next = ln7;
ln7.next = ln8;
ln8.next = ln9;
LeetCodeUtil.printNodeList(reverseBetween(ln1, 3, 7));
}
public static ListNode reverseBetween(ListNode head, int m, int n)
{
if (head == null || head.next == null)
{
return head;
}
ListNode fakeHead = new ListNode(0), prev = fakeHead, curr = null, next = null;
prev.next = head;
for (int i = 1; i <= n; i++)
{
if (i < m)
{
prev = prev.next;
}
else if (i == m)
{
curr = prev.next;
next = curr.next;
}
else
{
curr.next = next.next;
next.next = prev.next;
prev.next = next;
next = curr.next;
}
}
return fakeHead.next;
}
}