欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

链表的反转(复杂程序的编写方式)

程序员文章站 2022-07-10 21:07:43
...

 

链表反转:

 

思路一:

 

利用q p(移动,前后相对位置不变(套换工具))重置相邻节点的指针方向,r(移动,执行循环)标志剩下需要调整的链

  对象是引用传递,不是值引用

 

 

    //链表倒转---围绕核心操作展开一系列操作的编程方式,先编核心,然后缺的再补

 

  1,当前节点的下一节点的指向指向前一节点,由此引出修改当前节点下一节点指向时需要备份下一节点(实现备份与移位)

  2,前一节点移到当前节点,当前节点移到下一节点(通过赋值实现移位)

 

 类似编程方式2--树的遍历

     先画出思路图,然后一级一级需求实现,缺的后面补,重复的抽象

 

在画界线,粒度的时候最好每部分做不同的事情相互不参杂,然后再调整

 

 

  参考:

  https://www.cnblogs.com/mafeng/p/7149980.html

 

 

思路二:

  通过上一节点,当前节点,下一节点,三点的顺序移动的过程改变指向(没循环一次变一次指向),最后返回前一节点(到了最后节点之后,在会进入一次循环,此时下一节点是空,前一节点就是最后一节点

  )

顺序变动的全部在循环内赋值,只有开始传入的头在循环外赋值为当前节点

 

 

public class Node<E> {

   

   private E data;

 

   private Node<E> next;

 

   public Node(E node){///构造函数指赋值数据变量

       this.data=data;

   }

 

   public E getData(){

      return data;

   }

 

   public void setData(E data){

     this.data=data;

   

   }

 

   public Node getNext(){

       return next;

   }

 

 

   public void setNext(Node<E> next){

   this.next=next;

   

   }

    

 

}

 

 //指针遍历用迭代,树形最好用递归

 

public  static  Node<String> reverseList(Node<String> head){

 

     if(head ==null){

         return null;

     }

 

     if(head.getNext() ==null){

        return head;

     }

 

     //上面情况校验通过才可以进入倒转

 

     Node<String> preNode = null;

     Node<String> curNode =head;

     Node<String>  nextNode=null;

 

     while(curNode !=null){   //校验最后一个节点跳出

 

        nextNode = curNode.getNetx(); //操作之前备份出来,一个闭环,重新指向当前节点,当前节点的下一个即可实现三个节点的移动,先改当前节点下的下一节点,再改当前节点,实现next备份与移位

 

curNode.setNext(preNode);    //改变指向---倒转关键,next为preNode的引用,之后preNode变了,这里的不会变(值引用--值的副本(基本类型),对象引用--原始地址对象--赋值之后中间变量变了,之前赋值的不会变

 

preNode = curNode;   //实现prenode移位

 

curNode=nextNode;  //实现curnode移位

 

 

     

     

     

     }

 

 

   return preNode;

 

 

 

}

 

 

 

public class mainRun{

 

         public static void main(String[] arg0){

            Node node0 = new Node("1");

    Node node1 = new Node("2");

    Node node2 = new Node("3");

 

    node0.setNext(node1);

    node1.setNext(node2);

 

    Node head1 = node0;

 

           while(head1 !=null){

      head1=head1.getNext();

   }

 

           Node oldHead = node0;

   Node newHead = reverseList(oldHead);

 

   while(newHead !=null){

      newHead= newHead.getNext();

   }

 

 

 

}

 

 

 

 

}

 

 

 

参考

 

 

https://blog.csdn.net/qq_24692041/article/details/62424548

 

 

相关标签: 数据结构