package Singlelinkedlistpointerinversion;
/**
* @author 真他喵的学不动咯
* @create 2022-08-10--19:24
*/
public class Pointertoreverse { //单链表指针反转
//实现一个单链表
//内部类
public static class Node{
//属性
public int value;
public Node next;
//构造器
public Node(int data){
value=data;
}
}
//rever方法
public static Node reverse(Node head){
Node pre =null;
Node next=null;
while (head!=null){ //如果没跳到最后的null
next=head.next;//记录第二个位置
head.next=pre;
pre=head;
head=next; //相当于把head指针一直向那个方向传递,直到传递到null的最近位置
}
return pre; //此时,pre就是null最近的值,把pre作为头结点返回
}
//主函数
public static void main(String[] args){
Node n1=new Node(123);
n1.next=new Node(456);
n1.next.next=new Node(789);
//这样n1就是一个头指针
n1=reverse(n1); //原来的头指针是n1,现在反转以后,内容变了,把头指针还是重新赋给n1,
//n1一直是头指针,但是n1已经不是原来的n1,从头变成尾
//这样n1能够继续使用
while (n1!=null){ //打印一下看看结果,如果n1不是空的,那就打印n1的Value
System.out.println(n1.value+" ");
n1=n1.next; //把n1继续向下跳
}
System.out.println();
}
}