栈的应用
题目:输入一个链表,反转链表后,输出链表的所有元素。
1 /* 2 public class ListNode { 3 int val; 4 ListNode next = null; 5 6 ListNode(int val) { 7 this.val = val; 8 } 9 }*/ 10 import java.util.Stack; 11 public class Solution { 12 public ListNode ReverseList(ListNode head) { 13 if(head == null){ 14 return null; 15 } 16 Stack<Integer> stk = new Stack<Integer>(); //声明栈(泛型) 17 stk.push(head.val); 18 ListNode temp = head; 19 while(temp.next != null){ 20 stk.push(temp.next.val); //链表数据入栈 21 temp = temp.next; 22 } 23 head.val = stk.pop(); //整个过程中,head的地位不变化,就不用重新定义新的newhead 24 temp = head.next; 25 while(! stk.isEmpty()){ 26 temp.val = stk.pop(); 27 temp = temp.next; 28 } 29 return head; 30 } 31 }