2021/7/26
题目:先用一种迭代,话说第二种我明天再搞明白🍣
思路:乱七八糟的分析过程😓
话不多说,直接上代码段:
思想就是当不会的时候一定要先画图,把思想理清楚才能用好迭代(🐎的,我好啰嗦)
public class test {
static class Listcode{
int val;
Listcode next;
public Listcode(int val,Listcode next){
this.next=next;
this.val=val;
}
}
//迭代遍历,使用for循环(知道结束循环的长度)和while循环(不知道长度,只知道条件)的选择
public static Listcode iterate(Listcode head){
Listcode prev=null;
Listcode next=null;
Listcode curr=head;
while(curr != null)//循环的结束条件
{
next = curr.next;//指针保存,不然会丢失链接
curr.next=prev;//不要将curr.next赋值为空,要找一个非特殊情况,即当前节点的下一个变成了前一个
prev = curr;//当前节点和前置节点都是随着循环的进行倒着推进的
curr = next;
}
return prev;//为什么要返回前一个结点。因为curr已经变成了null,prev是新的头节点,作为链表,只需要知道头节点
}
public static void main(String[] args){
Listcode node5 = new Listcode(5,null);//链表的尾部
Listcode node4 = new Listcode(4,node5);
Listcode node3 = new Listcode(3,node4);
Listcode node2 = new Listcode(2,node3);
Listcode node1 = new Listcode(1,node2);
Listcode head = iterate(node1);
System.out.println(head);
}
}