zoukankan      html  css  js  c++  java
  • 反转链表2

        题目:

        反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

        说明:
        1 ≤ m ≤ n ≤ 链表长度。

        示例:

        输入: 1->2->3->4->5->NULL, m = 2, n = 4
        输出: 1->4->3->2->5->NULL

        来源:力扣(LeetCode)
        链接:https://leetcode-cn.com/problems/reverse-linked-list-ii

    static ListNode reverse(ListNode head,int m,int n){
          /*反转的前一个节点*/
            ListNode h=null;
          /*反转的第一个节点*/
          ListNode h1=null;
          /*反转末尾的后一个节点*/
            ListNode t=null;
          /*反转末尾的节点*/
          ListNode t1=null;
          /*当前节点*/
            ListNode curr=head;
            /*临时节点*/
            ListNode pre=null;
            int count=1;
            while (curr!=null){
              /*记录反转的前一个节点*/
                if(count+1==m){
                  h=curr;
                  curr=curr.next;
                  count++;
                  continue;
                }
                /*小于m的不需要反转*/
                if(count<m){
                  curr=curr.next;
                  count++;
                  continue;
                }
                /*记录反转的第一个节点*/
                if(count==m){
                  h1=curr;
                }
                /*记录反转末尾的后一个节点*/
                if(count==n+1){
                  t=curr;
                }
                /*大于n的不需要反转*/
              if(count>n){
                curr=curr.next;
                count++;
                continue;
              }
              /*记录反转末尾的节点*/
                if(count==n){
                  t1=curr;
                }
              count++;
                /*记录当前节点的后一个节点*/
                ListNode temp=curr.next;
                /*赋值当前节点的下一个节点是临时节点*/
                curr.next=pre;
                /*赋值临时节点为当前节点*/
                pre=curr;
                /*当前节点赋值为下一个节点,继续遍历*/
                curr=temp;
            }
            /*反转的前一个节点的下一个节点赋值为反转末尾的节点*/
            if(h!=null){
              h.next=t1;
            }
            /*反转的第一个节点的下一个节点为反转末尾的后一个节点*/
            if(h1!=null){
              h1.next=t;
            }
            /*如果m不是第一个节点则返回入参的节点*/
            if(m>1){
              return head;
            }
            /*返回第一个节点*/
            return pre==null?head:pre;
        }
    View Code
    @Data
        public static class ListNode{
            private int value;
            private ListNode next;
    
            public ListNode(int value){
                this.value=value;
            }
        }
    View Code
  • 相关阅读:
    LINNX联网配置文件
    linux文件系统配置文件
    linux引导和登录/注销配置文件
    LINUX访问文件配置
    LINUX配置文件介绍
    tcpdump的表达式介绍
    tcpdump命令介绍
    DNS客户端配置文件/etc/resolv.conf
    tcpdump概述
    LINUX普通猫的拔号工具介绍
  • 原文地址:https://www.cnblogs.com/wuyouwei/p/11764633.html
Copyright © 2011-2022 走看看