zoukankan      html  css  js  c++  java
  • 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) {
            ListNode newhead = new ListNode(-1);
            newhead.next = head;
            
            if(head==null||head.next==null)
                return newhead.next;
                
            ListNode startpoint = newhead;//startpoint指向需要开始reverse的前一个
            ListNode node1 = null;//需要reverse到后面去的节点
            ListNode node2 = null;//需要reverse到前面去的节点
            
            for (int i = 0; i < n; i++) {
                if (i < m-1){
                    startpoint = startpoint.next;//找真正的startpoint
                } else if (i == m-1) {//开始第一轮
                    node1 = startpoint.next;
                    node2 = node1.next;
                }else {
                    node1.next = node2.next;//node1交换到node2的后面
                    node2.next = startpoint.next;//node2交换到最开始
                    startpoint.next = node2;//node2作为新的点
                    node2 = node1.next;//node2回归到node1的下一个,继续遍历
                }
            }
            return newhead.next;
        }
        }

    https://www.cnblogs.com/springfor/p/3864303.html

    class Solution {
        public ListNode reverseBetween(ListNode head, int m, int n) {
            if(head == null) return null;
            ListNode dummy = new ListNode(-1);
            ListNode pre = dummy;
            dummy.next = head;
            for(int i = 0; i < m - 1; i++) {
                pre = pre.next;
            }
            
            ListNode cur = pre.next;
            for(int i = 0; i < n-m; i++) {
                ListNode move = cur.next;
                cur.next = move.next;
                move.next = pre.next;
                pre.next = move;            
            }
            return dummy.next;
        }
    }

    和25保持一致的写法,少记点幺蛾子屮

  • 相关阅读:
    MySQL中的错误
    [Err] 1064
    表单元素input 、button都要放进form里面
    【电商15】floor tab选项卡
    css三大特性——继承性:继承哪些样式
    border影响盒子大小-解决办法:
    padding影响&不影响盒子实际大小的情况
    【电商14】recom
    单行的多余文字,用省略号显示
    放精灵图的小盒子:_______;放字体图标:_______
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11330583.html
Copyright © 2011-2022 走看看