《剑指offer》从尾到头打印链表

【 声明:版权所有,转载请标明出处,请勿用于商业用途。  联系信箱:[email protected]


题目链接:http://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035?rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking


题目描述
输入一个链表,从尾到头打印链表每个节点的值。


思路

因为链表只能一条路往下走,无法回头,但是我们却需要让最后的点最先输出,怎么办呢?

没错,就是栈。我们可以在遍历链表的时候使用栈把所有结点存起来,最后再统一输出


/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(struct ListNode* head) {
        stack<ListNode*> S;
        ListNode *cur = head;
        while(cur)
        {
        	S.push(cur);
        	cur = cur->next;
		}
		vector<int> ans;
		while(!S.empty())
		{
			cur = S.top();
			S.pop();
			ans.push_back(cur->val);			
		}
		return ans;
    }
};


你可能感兴趣的:(剑指offer,牛客网)