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;
        }
    };
    
  • 相关阅读:
    Linux学习--线程概念
    菱形继承
    C++类型萃取
    Linux学习--进程创建
    Linux学习--进程概念
    比较全面的gdb调试命令
    再度理解原码、反码、补码
    详谈C++虚函数表那回事(多重继承关系)
    【sparkStreaming】将DStream保存在MySQL
    【sparkStreaming】kafka作为数据源的生产和消费
  • 原文地址:https://www.cnblogs.com/cling-cling/p/12895339.html
Copyright © 2011-2022 走看看