码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 92. Reverse Linked List II

时间:2016-06-02 06:13:20      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

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->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.


解题思路:

反转整个链表的变种,指定了起点和终点。由于m=1时会变动头节点,所以加入一个dummy头节点
 
1. 找到原链表中第m-1个节点start:反转后的部分将接回改节点后。
从dummy开始移动m-1步
 
D->1->2->3->4->5->NULL
       |
      st
 
2. 将从p = start->next开始,长度为L = n-m+1的部分链表反转。
            __________
            |                  |
            |                 V
D->1->2<-3<-4    5->NULL             
       |     |           | 
      st    p          h0         
 
3. 最后接回
 
            __________
            |                  |
            |                 V
D->1   2<-3<-4    5->NULL             
       |________|                

 


Java code:
20160601
/**
 * 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) {
        //iterative
        //base case
        if (head == null || head.next == null || m < 1 || m >= n) {
            return head;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        ListNode cur = head;
        //move m-1 to the node before reverse start 
        int count = 1;
        while (count < m) {
            pre = cur;
            cur = cur.next;
            count++;
        }
        ListNode beforeReverse = pre;
        ListNode startReverse = cur;
        
        while (count <= n) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
            count++;
        }
        beforeReverse.next = pre;
        startReverse.next = cur;
        return dummy.next;
    }
}

 


Reference:

1. http://bangbingsyb.blogspot.com/2014/11/leetcode-reverse-linked-list-ii.html
 

 

Leetcode 92. Reverse Linked List II

标签:

原文地址:http://www.cnblogs.com/anne-vista/p/5551671.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!