链表的反转(复杂程序的编写方式)
链表反转:
思路一:
利用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
推荐阅读
-
java创建数组的几种方式(java编写图形界面程序)
-
微信小程序授权 获取用户的openid和session_key【后端使用java语言编写】,我写的是get方式,目的是测试能否获取到微信服务器中的数据,后期我会写上post请求方式。
-
韦东山uboot_内核_根文件系统学习笔记5.8-第005课_字符设备驱动_第008节_第008节_字符设备驱动程序之中断方式的按键驱动_编写代码
-
链表的反转(复杂程序的编写方式)
-
“一帮一学习小组”是中小学中常见的学习组织方式,老师把学习成绩靠前的学生跟学习成绩靠后的学生排在一组。本题就请你编写程序帮助老师自动完成这个分配工作,即在得到全班学生的排名后,在当前尚未分组的学生中,
-
微信小程序授权 获取用户的openid和session_key【后端使用java语言编写】,我写的是get方式,目的是测试能否获取到微信服务器中的数据,后期我会写上post请求方式。
-
S3C2440 字符设备驱动程序之中断方式的按键驱动_编写代码(七)
-
ExtJS 中使用Asp.net编写后台服务器程序的几种方式