您的位置:首页 > 其它

leetCode 92.Reverse Linked List II (反转链表II) 解题思路和方法

2015-07-27 09:50 567 查看
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; }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
/**
* 本题思想是将m,n中间的链表遍历,同时计数
* 3放在2前面,1-3-2-4-5
* 然后4放在3前面,1-4-3-2-5
* 当计数到了,结束循环
*/
ListNode first = new ListNode(0);
//头结点,方便统一处理
first.next = head;

ListNode temp = null;
ListNode p = null;
ListNode pHead = first;//不需要反转的最后一个节点
ListNode pLast = null;//需要反转节点的第一个节点,将反转到最后

int len = 0;
while(head != null){
if(++len < m){
pHead = head;//记录未变动的节点末尾值,如例题中的1
head = head.next;
}
else if(len == m){
//记录开始位置
p = pLast = head;
head = head.next;
pLast.next = null;//此句很重要,斩断之后的连接
}else if(len >= m && len <= n){
//新插入节点
temp = head;
head = head.next;//必须放这里,不然出错
temp.next = p;
p = temp;
pHead.next = p;
}else if(len > n){
pLast.next = head;//将已交换的链表连接上不需交换的末尾,如本例5
break;
}

}

return first.next;
}

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