题目:
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
.
分析:
1. 链表可能从表头开始反转,因此需要dummy node。
2. 先找到链表的第n个节点,即第一个需要反转的节点,为了之后指定部分整体反转,先记下它的前节点。
3. 对需要反转的部分进行反转。
4. 把2中记下的前节点的next更新成第m个节点,第n个节点的next更新为m+1个节点。反转完成。
Java代码实现:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head == null || head.next == null || m==n)
return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
for(int i=1;i<m;i++)
pre = pre.next;
ListNode node = pre.next;
ListNode next = node.next;
ListNode temp = new ListNode(0);
for(int i=m;i<n;i++)
{
temp = next.next;
next.next = node;
node = next;
next = temp;
}
pre.next.next = temp;
pre.next = node;
return dummy.next;
}
}