leetcode-92 Reverse Linked List II

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

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

 

/**
 * 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) {
        if(m == n) {
            return head;
        }
        ListNode tmpA = head;
        ListNode tmpBegin = null;
        ListNode lastNow = null; 
        
        ListNode res = head;
        if(m > n) {
            int tmp = m;
            m = n;
            n = tmp;
        }
        int index=1;
        while(index<=n) {
            if(index==m) {
                tmpBegin = tmpA;
                lastNow = tmpA;
                tmpA = tmpA.next;
            }else if(index>m) {
                ListNode now = tmpA;
                ListNode tAfter = now.next;
                now.next = lastNow;
                tmpBegin.next = tAfter;
                tmpA = tmpBegin.next;
                lastNow = now;
            }else {
                tmpA = tmpA.next;
            }
            index++;
            if(index<m) {
                res = res.next;
            }
        }
        if (m == 1) {
            return lastNow;
        } else {
            res.next = lastNow;
            return head;
        }  
    }
}

 

用3个节点进行替换如1-2-3-4-5中先找出节点2为(tmpBegin不会改变)起始节点,3为当前节点 旋转后变为1-3-2-4-5,此时上一个开始节点(lastNow)变为节点3 ,在通过指定       now.next = lastNow ; tmpBegin.next = tAfter; 变为1-4-3-2-5

(lastNow为上一次旋转后的起始节点 第一次为2 旋转后为3 在旋转后变为4)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值