链表逆序输出数值
2019-04-09 本文已影响0人
firststep
链表学习
今天学习链表的时候,遇到这样一个问题,如何把链表逆序输出。拿到这道题首先想到的结构就是"栈"结构,因为它是按照先进后出的方式刚好适合链表的逆序。
代码学习
Node.java
package likendListStudy;
public class Node {
private int data;
private Node nest = null;
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getNest() {
return nest;
}
public void setNest(Node nest) {
this.nest = nest;
}
public Node() {
}
public Node(int data) {
this.data = data;
}
}
代码内核
package likendListStudy;
import java.util.Stack;
public class ReverseLinkedList {
public Node createLinkedList() {
Node node = new Node(1);
Node node1 = new Node(2);
Node node2 = new Node(3);
Node node3 = new Node(4);
Node node4 = new Node(5);
node.setNest(node1);
node1.setNest(node2);
node2.setNest(node3);
node3.setNest(node4);
return node;
}
// 用栈的方式来输出
public void printListforStatic(Node node) {
Stack<Integer> stack = new Stack<>();
while (node != null) {
stack.push(node.getData());
node = node.getNest();
}
while (!stack.isEmpty()) {
System.out.print(stack.pop()+" ");
}
}
public static void main(String args[]) {
ReverseLinkedList reverseLinkedList = new ReverseLinkedList();
Node node = reverseLinkedList.createLinkedList();
reverseLinkedList.printListforStatic(node);
}
}