单链表的反转 - 三指针版

当创建一个链表后,链表只知道自己的下一个节点,而不知道自己的上一个节点,为了能够让节点知道上一个节点,我们需要这样做。
1、创建三个指针 一个是沿着原来的链表进行遍历,一个存储,一个用于交换
2、进行将链表反向的工作
比如: 原来链表 0 -> 1 -> 2 -> 3 -> 4…-> n ->NULL;
用代码来表示就是 0.next = 1 1.next = 2 2.next = 3 3.next = 4 等等
我们需要变成的是 n -> n-1 -> … -> 4 -> 3 -> 2 -> 1 -> 0 -> NULL
用代码来表示就是 n.next = n-1 4.next = 3 3.next = 2 2.next = 1 1.next = 0 0.next = NULL

下面这块代码的三个指针
current : 遍历指针
temp : 用于存储的指针
point : 指向需要交换的值

比如第一轮while是这样的
*刚开始 current = 0 temp = NULL point = NULL (我们想要的效果是 0.next = NULL) 所以最终想要得到的表达式是 current.next = point 但是为了进行下一轮的循环 可以用temp来代替current 让 current继续迭代 就是 temp.next = point

public void Reverse(){
	Node current = first;   //这是用于遍历的指针
	Node temp = null; //用于存储的指针
	Node point = null; //用于交换的指针
	System.out.println("反转后的链表 : ");
	while(current != null){
		point = temp;
		temp = current;
		current = current.next;
		temp.next = point;
	}
	current = temp;  //得到反转后的Head指针
	while(current != null){
		System.out.println(current.data);
		current = current.next;
	}
	System.out.println();
}

猜你喜欢

转载自blog.csdn.net/weixin_43635647/article/details/104110439