*92. Reverse Linked List II (follow up questions)

Reverse a linked list from position m to n. Do it in one-pass and in-place

Note: 1 ≤ m ≤ n ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL

FIrstly, I wanna use stack but need cosume space

Finally, I use in-plcae method

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

 
反转整个链表的变种,指定了起点和终点。由于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             
       |________|                

In code

1. dfine dummy node

2. find the start node

3. reverse the node

4. connect the list

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode d = new ListNode(0);
        d.next = head;
        //find start point(head )
        ListNode pre = d; 
        for(int i = 0; i<m-1; i++){
            pre = pre.next;
            head = head.next;
        }
        ListNode tailReverse = head;
        ListNode end = null, temp;
        for(int i = 0; i<n-m+1; i++){ // need +1
            temp = head.next;
            head.next = end;
            end = head;
            head = temp;
        }
        //System.out.println(end.val);
        pre.next = end;
        tailReverse.next = head;
        return d.next; 
    }
}
posted @ 2018-08-06 06:51  wz30  阅读(187)  评论(0编辑  收藏  举报