zoukankan      html  css  js  c++  java
  • 【LeetCode】面试题06. 从头到尾打印链表

    题目:

    思路:

    单链表、递归
    要求输出数组,所以本题和单链表反转不同。通过reverse、栈、递归的思路求解。

    代码:

    Python

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def reversePrint(self, head):
            """
            :type head: ListNode
            :rtype: List[int]
            """
            result = list()
            # 尾插入 append之后reverse
            # while head is not None:
            #     result.append(head.val)
            #     head = head.next
            # result.reverse()  # 直接对result修改, 返回是None
            # return result
            # 头插入 insert(0, elem) 性能不如append
            while head is not None:
                result.insert(0, head.val)
                head = head.next
            return result
    

    C++

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        // vector<int> result;
        vector<int> reversePrint(ListNode* head) {
            // 栈
            vector<int> result;
            stack<int> st;
            while(head) {
                st.push(head->val);
                head = head->next;
            }
            while(!st.empty()) {
                result.push_back(st.top());
                st.pop();  // pop不能替代top, 不返回元素
            }
            return result;
            // 递归
            // if (!head) {
            //     return result;
            // }
            // reversePrint(head->next);
            // result.push_back(head->val);
            // return result;
        }
    };
    
  • 相关阅读:
    寒宣资料汇编
    Windows邮件客户端
    Dear Menuhin
    2017-11-11 Sa Oct Spider
    2017-11-11 Sa Oct How to open a browser in Python
    skynet游戏服务器框架分享
    钉钉 机器人接入 自定义webhook
    golang语法笔记
    [学习笔记]尝试go-micro开发微服务<第一波>
    [学习笔记]Golang--基础数据类型
  • 原文地址:https://www.cnblogs.com/cling-cling/p/12895339.html
Copyright © 2011-2022 走看看