python 剑指offer 链表尾首打印

输入一个链表,从尾到头打印链表每一个节点的值。python

python解法:先将链表中的值插入到序列l中,以后再将序列逆置,则输出序列便可c++


def printListFromTailToHead(self, listNode):
        l=[]
        while listNode:
            l.append(listNode.val)
            listNode=listNode.next
        l.reverse()
        return l数组


c++解法:app

思路:先将链表中的元素压入栈中,而后将栈中元素弹出到动态数组中,即实现逆序List


vector<int> printListFromTailToHead(ListNode* head) {
        stack<int> stack1;
        vector<int> res;
        while(head)
        {
           stack1.push(head->val);
            head=head->next;
        }
        while(!stack1.empty())
       {
            res.push_back(stack1.top());
            stack1.pop();
        }
        return res;
    }链表

相关文章
相关标签/搜索