您的位置:首页 > 其它

92. Reverse Linked List II

2016-09-14 22:00 369 查看
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的差值找到这起始和终止节点的位置,(注意m、n的大小关系)应该是n-m 开始写成了m-n

  因为要在inplace内完成 所以不能建新的辅助链表。所以:

将原来的链表分成三段,开始一段,需要反转的一段,结束的一段(注意如何找到这三段的起始节点)

将需要反转的一段从头开始反向接到结束一段的开头

需要注意记录关键辅助节点

 

返回头结点是 需要将原来的头结点保留!!

public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
int len=n-m;int cnt=m;
ListNode start=new ListNode(0);
start.next=head;
ListNode end=start;
ListNode finalhead=start;
while(len>0){
end=end.next;
len--;
}
while(cnt>1){
end=end.next;
start=start.next;
cnt--;
}
ListNode newhead1=start;

start=start.next;
end=end.next;
newhead1.next=null;
ListNode newhead2=end.next;
end.next=null;
while(start!=null){
ListNode startnew=start;

start=start.next;
startnew.next=newhead2;
newhead2=startnew;
}
newhead1.next=newhead2;
return finalhead.next;
}
}
https://discuss.leetcode.com/topic/8976/simple-java-solution-with-clear-explanation
12345——13245——14235    把需要调整位置的前一个节点(pre)记录下来不断的将第一个需要调整位置(2)之后的节点(3、4)插到1后  根据差值m-n控制调整的次数

public ListNode reverseBetween(ListNode head, int m, int n) {
if(head == null) return null;
ListNode dummy = new ListNode(0); // create a dummy node to mark the head of this list
dummy.next = head;
ListNode pre = dummy; // make a pointer pre as a marker for the node before reversing
for(int i = 0; i<m-1; i++) pre = pre.next;

ListNode start = pre.next; // a pointer to the beginning of a sub-list that will be reversed
ListNode then = start.next; // a pointer to a node that will be reversed

// 1 - 2 -3 - 4 - 5 ; m=2; n =4 ---> pre = 1, start = 2, then = 3
// dummy-> 1 -> 2 -> 3 -> 4 -> 5

for(int i=0; i<n-m; i++)
{
start.next = then.next;
then.next = pre.next;
pre.next = then;
then = start.next;
}

// first reversing : dummy->1 - 3 - 2 - 4 - 5; pre = 1, start = 2, then = 4
// second reversing: dummy->1 - 4 - 3 - 2 - 5; pre = 1, start = 2, then = 5 (finish)

return dummy.next;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: