题目链接https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
题目描述
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)
输入:head = [1,3,2]
输出:[2,3,1]
解题思路
使用栈依次存入节点,然后再从栈中取出节点可实现逆序,即从尾到头打印链表
程序源码
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: vector<int> reversePrint(ListNode* head) { vector<int> revResult; stack<int> sk; while(head != nullptr) { sk.push(head->val); head = head->next; } while(!sk.empty()) { revResult.push_back(sk.top()); sk.pop(); } return revResult; } };