您的位置:首页 > 其它

Reverse Linked List II

2017-09-28 21:35 225 查看
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.

思路:

之前有做过把整个链表逆置的题,本题经过修改,变成了对链表中的部分进行逆置(第m个节点到第n个节点之间)。

模拟一下逆置的过程:

比如2-3-4-5,先把3放2前面变成3-2-4-5,再把4放3-2前面变成4-3-2-5,再把5放4-3-2前面变成5-4-3-2。

循环该怎么做?

第一步,找到m处的节点start,同时需要它的前驱pre与后继then。其实是先找pre,然后start是pre的后继,then又是start的后继。

第二部,利用pre,start,then这三个指针,从m+1到n的节点,依次放置到pre的后面。pre是永远不动的,因为插入的节点都需要插入

它的后面,而start和then每次需要向后移动。

public class ReverseLinkedListII {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head == null)
return null;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
for(int i=0; i<m-1; i++) {
pre = pre.next;
}
ListNode start = pre.next;
ListNode then = start.next;
for(int i=0; i<n-m; i++) {
start.next = then.next;
then.next = pre.next;
pre.next = then;
then = start.next;
}
return dummy.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: