• [LeetCode] 92. Reverse Linked List II Java


    题目:

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

    For example:
    Given 1->2->3->4->5->NULLm = 2 and n = 4,

    return 1->4->3->2->5->NULL.

    Note:
    Given mn satisfy the following condition:
    1 ≤ m ≤ n ≤ length of list.

    题意及分析:反转链表从m到n的节点,其中1 ≤ m ≤ n ≤ length of list。主要是要用一个preNode记录当前点前一个点和nextNode记录当前点后一个点,这样就可以将当前点的next指针指向preNode,然后将preNode = node, node = nextNode,继续交换后面的点即可。注意的是m==1,即从第一个点开始翻转时有一点不同。

    代码:

    /**
     * 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 startNode = head; //记录m-1的点
            ListNode preNode = head;        //记录当前点的前一个点
            ListNode nextNode = head; //记录当前点的下一个点
            ListNode node = head;
            int index = 1;
            if(m==1){       //第一个点开始翻转
                while(index <= n){
    //                node = node.next;
                    nextNode = node.next;       //记录下一个点
                    if(index !=1){      //不是第一个点就交换指针
                        node.next = preNode;
                        preNode = node;
                    }
                    node = nextNode;
                    index++;
                }
                startNode.next = node;
                return preNode;
            }else{      //后面点开始翻转
                ListNode temp = null;
                while(index <=n){
                    if(index == m-1) {      //记录翻转点前一个点
                        startNode = node;
                        temp = node.next;
                    }
                    nextNode = node.next;       //记录下一个点
                    if(index !=1 && index > m){      //不是第一个点就交换指针
                        node.next = preNode;
                    }
                    preNode = node;
                    node = nextNode;
                    index++;
                }
                startNode.next = preNode;
                temp.next = node;
                return head;
            }
        }
    }
  • 相关阅读:
    mybatis批量更新策略
    tk.mybatis扩展通用接口
    IDEA入门——jdbc连接和工具类的使用
    tensorflow——3
    再战tensorflow
    tensorflow初学
    Anaconda和TensorFlow安装遇到的坑记录
    《企业应用架构模式》——阅读笔记3
    机器学习十讲——第十讲
    机器学习十讲——第九讲
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7997568.html
Copyright © 2020-2023  润新知