劍指offer——面試題5:從尾到頭打印鏈表

package offer;

import java.util.Stack;

/**
 * 輸入一個鏈表的頭結點,從尾到頭反過來打印出每一個節點的值
 */
public class Problem05 {

	public static void main(String[] args) {
		LinkList list = new LinkList();
		list.head = new Node(1);
		list.head.next = new Node(2);
		list.head.next.next = new Node(3);
		Stack<Node> stack = new Stack<>();//重點:利用棧的特性
		Node current = list.head;
		while (current != null) {
			stack.push(current);
			current = current.next;
		}
		while (!stack.isEmpty()) {
			System.out.print("-->" + stack.pop().data);
		}
	}

}

class LinkList {
	Node head;
}

class Node {
	public double data;
	public Node next;

	public Node(double data) {
		this.data = data;
	}
}
相關文章
相關標籤/搜索