zoukankan      html  css  js  c++  java
  • 算法总结之 反转部分单向链表

    给定单链表的表头节点head, 以及两个整数from 和 to, 在单向链表上把fro个节点到第to个节点这一部分进行反转

    思路:

      本题 有可能存在换头的问题,所以函数应该返回调整后的新的头节点

      1 判断是否满足 1<=from<=to<=N 如果不满足,直接返回原来的头节点

      2 找到第from-1个节点pre和第to+1个节点tPos,fPre即要反转部分的前一个节点,tPos是反转部分的后一个节点,把反转部分先反转,然后正确的链接fPre和tPos

    package TT;
    
    import TT.Test85.Node;
    
    public class Test90 {
    
        public Node reversePart(Node head, int from , int to){
            int len = 0;
            Node node1=head;
            Node fPre = null;
            Node tPos = nullwhile(node1!= null){ 
               len++;
               fPre = len == from-1 ? node1 : fPre;
               tPos = len== to+1 ? node1 : tPos;
               node1 =node1.next;
           }
            if(from<to || from<1 || to>len){
                return head;
            }
            node1 = fPre==null ? head:fPre.next;
            Node node2 = node1.next;
            node1.next = tPos;
            Node next = null;
            while(node2 !=tPos){
                 next = node2.next;
                 node2.next = node1;
                 node1 = node2;
                 node2 = next;
            }
            if(fPre != null){
                fPre.next=node1;
                return head;
            }
            return node1;
        }
        
        
        
    }
  • 相关阅读:
    华硕B360主板装机找不到固态硬盘启动
    Maxwell平滑升级流程
    快速导入Excel数据到mysql
    Docker
    Rest之路
    Rest之路
    Docker -- resolve "join node timeout" error
    (转) Docker
    Docker
    Docker
  • 原文地址:https://www.cnblogs.com/toov5/p/7499427.html
Copyright © 2011-2022 走看看