题目:从尾到头打印一个单链表
方法:
很容易的就想到了栈先进后出的特性,可以把链表从头到尾遍历,同时将结点入栈,然后将栈中的元素依次弹出。
package offer;
import java.util.Stack;
import dataStruct.List;
import dataStruct.List.ListNode;
public class offer5_PrintList {
public static void main(String[] args) {
List list = new List();
int[] datas = {7,6,5,4,3,2,1};
ListNode head = list.createList(datas);
offer5_PrintList.printListFromTailToHead(head);
}
/**
* 从尾到头打印链表
* @param headNode
*/
public static void printListFromTailToHead(ListNode headNode) {
Stack<ListNode> stack = new Stack<>();
ListNode node = headNode.next;
if(node == null){
System.out.println("list is null");
}
while(node != null){
stack.push(node);
node = node.next;
}
while(!stack.isEmpty()){
System.out.println(stack.pop().val+"");
}
}
}