zoukankan      html  css  js  c++  java
  • 从尾到头打印链表

    题目描述

    输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

    python:

     1 # -*- coding:utf-8 -*-
     2 # class ListNode:
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.next = None
     6 
     7 class Solution:
     8     def printListFromTailToHead(self, listNode):
     9         lst , back_lst = [],[]
    10         while not listNode:
    11             return lst
    12         while listNode:
    13             lst.append(listNode.val)
    14             listNode = listNode.next
    15         while lst:
    16             back_lst.append(lst.pop())
    17         return back_lst

    思想:

    先入栈,进入lst(lst是入栈的列表)

    然后再出栈,lst.pop,得到的就是反转链表。back_lst是出栈的列表。

    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         vector<int> res;
    14         stack<int> temp_stack;
    15         if(!head) return res;
    16         while(head){
    17             temp_stack.push(head->val);
    18             head = head->next;
    19         }
    20         while(!temp_stack.empty()){
    21             res.push_back(temp_stack.top());
    22             temp_stack.pop();
    23         }
    24         return res;
    25     }
    26 };
  • 相关阅读:
    能用HTML/CSS解决的问题,就不要用JS
    跨域
    从输入url到页面展示到底发生了什么
    hosts 文件
    了解Web及网络基础
    hybrid
    组件化和 React
    MVVM 和 VUE
    虚拟 DOM
    ES6模块化与常用功能
  • 原文地址:https://www.cnblogs.com/pacino12134/p/10939095.html
Copyright © 2011-2022 走看看