• 5 从尾到头打印链表


    输入一个链表,从尾到头打印链表每个节点的值。
      方法一:用栈
      方法二:递归
      方法三:使用java中的 Collections.reverse()

    C++:

     1 /**
     2 *  struct ListNode {
     3 *        int val;
     4 *        struct ListNode *next;
     5 *        ListNode(int x) :
     6 *              val(x), next(NULL) {
     7 *        }
     8 *  };
     9 */
    10 class Solution {
    11 public:
    12     vector<int> printListFromTailToHead(ListNode* head) {
    13         if(head == NULL)
    14             return vector<int>() ;
    15         stack<int> s ;
    16         vector<int> res ;
    17         ListNode* p = head ;
    18         while(p != NULL){
    19             s.push(p->val) ;
    20             p = p->next ;
    21         }
    22         while(!s.empty()){
    23             res.push_back(s.top()) ;
    24             s.pop() ;
    25         }
    26         return res ;
    27     }
    28 };

    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 *
    11 */
    12 import java.util.*;
    13 public class Solution {
    14     public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
    15         Stack<Integer> stack = new Stack<>() ;
    16         while(listNode != null){
    17             stack.push(listNode.val) ;
    18             listNode = listNode.next ;
    19         }
    20         ArrayList<Integer> list = new ArrayList<>() ;
    21         while(!stack.isEmpty()){
    22             list.add(stack.pop()) ;
    23         }
    24         return list ;
    25     }
    26 }
  • 相关阅读:
    Redis数据类型之字符串String
    Redis数据类型之列表List
    hdu 2066 一个人的旅行
    CDOJ 1221 Ancient Go
    如何避免javascript中的冲突
    利用锚点制作简单索引效果
    函数中的私有变量和特权方法
    Linux中常用命令cat
    java -jar参数运行方式设置classpath
    Linux中的数据重定向
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/8906582.html
Copyright © 2020-2023  润新知