目录
一、问题详情
将链表进行逆序打印。
文章中只含有部分代码,在文章的最后附上全部的代码和运行的截图。
二、代码实现
1.创建和打印链表
节点类
创建链表的节点
class ListNode {
int value;//节点的值
ListNode next;//下一个节点
public ListNode(int value) {
this.value = value;
}
}
创建一个链表
创建一个简单链表的方法
//创建一个链表,用于测试
public void createList() {
ListNode cur = new ListNode(1);
ListNode head = cur;
for (int i = 2; i < 5; i++) {
cur.next = new ListNode(i);
cur = cur.next;
}
上面的代码利用循环创建了一个基本的链表,通过cur节点不断的连接新节点(新节点的值是for循环中的变量i) ,然后cur节点向后走,循环创建,用head来找到头节点的位置。这样一个链表就创建好了。
打印链表
拿到头节点,对链表进行遍历,每遍历一个节点,就打印一个值。
//打印链表
public void print(ListNode head) {
while (head != null) {
System.out.print(head.value+" ");
head = head.next;
}
}
2.递归逆序
代码介绍
通过对节点的递归,使节点走到最后,然后对节点的值进行打印。因此,递归结束的条件就是只剩下最后一个节点,即结束条件是最后节点的下一个节点为空。
//逆序打印单链表(递归)
public void reversePrintList(ListNode head) {
//如果只有一个头节点,直接输出
if(head.next == null) {
System.out.print(head.value+" ");
return;
}
reversePrintList(head.next);
System.out.print(head.value+" ");
}
由代码可以看出,每次递归,head节点就会向后走,直到递归完成,函数返回,执行打印的代码。
图解代码
如图,逆序递归打印一个有三个节点的链表,递归思想
3.使用栈逆序
代码介绍
利用栈的特性,后进先出,将链表中的元素全部放入栈中,然后进行出栈打印。
//逆序打印链表(栈实现)
//利用栈的特性,先进后出
public void stackReversePrintList(ListNode head) {
Stack<ListNode> stack = new Stack<>();
//节点不为空,直接放入栈中,并且链表节点向后移动
while(head != null) {
stack.push(head);
head = head.next;
}
//开始出栈
//当栈不为空
while(!stack.isEmpty()) {
//节点出栈,拿到结点的值
System.out.print(stack.pop().value+" ");
}
出栈打印我使用的是while循环,当栈为空时循环结束,打印完成。由此实现了链表的逆序打印。这种方法较为简答,相比于使用递归更容易理解
三、全部代码和运行代码(含运行截图)
1.全部代码
import java.util.Stack;
public class StackPractice {
class ListNode {
int value;
ListNode next;
public ListNode(int value) {
this.value = value;
}
}
//打印链表
public void print(ListNode head) {
while (head != null) {
System.out.print(head.value+" ");
head = head.next;
}
}
//创建一个链表,用于测试
public void createList() {
ListNode cur = new ListNode(1);
ListNode head = cur;
for (int i = 2; i < 5; i++) {
cur.next = new ListNode(i);
cur = cur.next;
}
System.out.print("原来的链表:");
print(head);
System.out.println();
//递归的方法逆序打印链表
System.out.print("递归逆序:");
reversePrintList(head);
System.out.println();
//利用栈方法逆序打印链表
System.out.print("用栈逆序:");
stackReversePrintList(head);
System.out.println();
}
//逆序打印单链表(递归)
public void reversePrintList(ListNode head) {
//如果只有一个头节点,直接输出
if(head.next == null) {
System.out.print(head.value+" ");
return;
}
reversePrintList(head.next);
System.out.print(head.value+" ");
}
//逆序打印链表(栈实现)
//利用栈的特性,先进后出
public void stackReversePrintList(ListNode head) {
Stack<ListNode> stack = new Stack<>();
//节点不为空,直接放入栈中,并且链表节点向后移动
while(head != null) {
stack.push(head);
head = head.next;
}
//开始出栈
//当栈不为空
while(!stack.isEmpty()) {
//节点出栈,拿到结点的值
System.out.print(stack.pop().value+" ");
}
}
}
2.运行代码
public class Test {
public static void main(String[] args) {
StackPractice stackP = new StackPractice();
stackP.createList();
}
}
创建Test类,作为运行的主类,打印操作我全部放在createList()这个方法里面了。
3.运行截图
四、总结
逆置链表的两种简单实现
1.利用递归的方法实现
2.利用栈实现
以上便是我对链表逆转的全部理解,如有问题欢迎评论区留言。