输入一个链表,从尾到头打印链表每个节点的值。

来源:互联网 发布:我的世界快速建造js 编辑:程序博客网 时间:2024/06/11 15:47

输入一个链表,从尾到头打印链表每个节点的值。

package Offer;import java.util.ArrayList;import java.util.List;import java.util.Stack;/*Created By guolujie 2017年10月18日*/class ListNode{int val;ListNode next = null;public ListNode(int val) {// TODO Auto-generated constructor stubthis.val = val;}}public class FanZhuanList {public static List Solution(ListNode listNode){Stack<Integer> stack = new Stack<Integer>();while (listNode != null) {stack.push(listNode.val);listNode = listNode.next;}List<Integer> list = new ArrayList<Integer>();while (!stack.isEmpty()) {list.add(stack.pop());}return list;}public static void main(String[] args) {// TODO Auto-generated method stubListNode node = new ListNode(1);ListNode node1 = new ListNode(2);ListNode node2 = new ListNode(3);node.next = node1;node1.next = node2;List<Integer> list = Solution(node);for (int i = 0; i < list.size(); i++) {System.out.print(list.get(i)+ " ");}}}


阅读全文
0 0