这是我看这本书和看其他人写的java代码,然后自己理解过后,写的代码,主要是参考:
https://blog.csdn.net/google19890102/article/details/40264699
先定义一个结点:
package 剑指offer;
public class LinkedList {
public String value;
public LinkedList next;
public LinkedList(String value, LinkedList next) {
this.value = value;
this.next = next;
}
}
package 剑指offer;
import java.util.Stack;
public class PrintLinkedList {
public static void main(String[] args) {
// 初始化一个链表
LinkedList node4 = new LinkedList("熊2", null);
LinkedList node3 = new LinkedList("赵六", node4);
LinkedList node2 = new LinkedList("王五", node3);
LinkedList node1 = new LinkedList("李四", node2);
LinkedList head = new LinkedList("张三", node1);
PrintLinkedList.printTest(head);
}
public static void printTest(LinkedList head) {
Stack<String> stack = new Stack<String>();
// 进栈
while (head.next != null) {
System.out.print(head.value);
stack.push(head.value);
head = head.next;
}
// 出栈
System.out.println();
while (!stack.isEmpty()) {
String str = stack.pop();
System.out.println(str);
}
}
}
控制台打印: