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

本文介绍了一种在链表中从位置m到n进行一次性、就地反转的方法,并提供了一个具体的示例来展示如何实现该算法。该算法适用于指定起点和终点的情况。

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; 
    }
}

转载于:https://www.cnblogs.com/stiles/p/leetcode92.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值