首页 > 其他 > 详细

[LC] 92. Reverse Linked List II

时间:2019-12-30 13:07:54      阅读:61      评论:0      收藏:0      [点我收藏+]

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) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        
        ListNode cur1 = dummy;
        ListNode pre1 = null;
        for (int i = 0; i < m; i++) {
            pre1 = cur1;
            cur1 = cur1.next;
        }
        
        ListNode cur2 = cur1;
        ListNode pre2 = pre1;
        ListNode nxt = null;
        for(int i = m; i <= n; i++) {
            nxt = cur2.next;
            cur2.next = pre2;
            pre2 = cur2;
            cur2 = nxt;
        }
        
        // connect 1 -> 4
        pre1.next = pre2;
        // connnect 2 -> 5
        cur1.next = cur2;
        
        return dummy.next;
    }
}

[LC] 92. Reverse Linked List II

原文:https://www.cnblogs.com/xuanlu/p/12118644.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!