【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;
    }
};
posted @ 2020-05-15 15:50  一只背影  阅读(97)  评论(0编辑  收藏  举报