/*
输入一个链表,从尾到头打印链表每个节点的值。
*/
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
std::vector<int> vecRet ;
if(head == NULL) return vecRet;
//DoIt(vecRet, head) ;
ListNode* pCurNode = head ;// avoid change input parameter head
std::stack<int> st ;
while(pCurNode) {
st.push(pCurNode->val) ;
pCurNode = pCurNode->next ;
}
while(!st.empty()) {
vecRet.push_back(st.top()) ;
st.pop() ;
}
return vecRet ;
}
void DoIt(std::vector<int>& vecRet, ListNode* head) {
if(head) {
if(head->next) {// if have next, first recurse
DoIt(vecRet, head->next) ;
}
vecRet.push_back(head->val) ; // then push it self
}
}
};
从尾到头打印链表
最新推荐文章于 2020-08-07 20:13:41 发布