zoukankan      html  css  js  c++  java
  • 栈的应用

    题目:输入一个链表,反转链表后,输出链表的所有元素。

     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 }
  • 相关阅读:
    数组的顺序存储表示
    CF538G Berserk Robot
    【LGR-077】洛谷 10 月月赛 I Div.1 && P6854 Tram
    [THUPC2019]找树
    CF536D Tavas in Kansas
    luogu「EZEC-4.5」子序列
    2020.8.7
    拉格朗日反演
    2020.8.6
    初赛复习
  • 原文地址:https://www.cnblogs.com/XuGuobao/p/7445518.html
Copyright © 2011-2022 走看看