标签:
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) {
if(head == null){
return null;
}
if(m == n){
return head;
}
int flag = 0;
ListNode p1 = head;//用来指向开始反转结点的前一个结点
ListNode p2 = head;//用来指向最后反转结点的后一个结点 p1---p2之间的结点是要反转的结点(不包含p1 p2)
ListNode phead = new ListNode(0);
phead.next = head;
ListNode p = phead;
while(p != null){
flag++;
if(flag == m){
p1 = p;//指向开始逆转结点的前一个结点
}
if(flag == n+1){
p2 = p.next;//指向结束逆转结点的后一个结点
break;
}
p = p.next;
}
ListNode pp1 = p1.next;
ListNode pp2 = pp1.next;
ListNode pp3 = pp2.next;
pp1.next = p2;
while(pp3 != p2){
pp2.next = pp1;
pp1 = pp2;
pp2 = pp3;
pp3 = pp3.next;
}
pp2.next = pp1;
p1.next = pp2;
return phead.next;
}
}
Leetcode 92. Reverse Linked List II
标签:
原文地址:http://blog.csdn.net/xinyuehuixin/article/details/51328997