#剑指 offer 06
题目描述:

这题表述的很明确了,从最末尾的元素开始输出,这让我们想到的数据结构就是栈了。
思路:先把链表中存储的数据压入栈中,然后弹出到一个动态数组vector中,最后返回数组。
/**
* 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) {
stack<int> s; //Create an empty stack
vector<int> c; //Create an empty vector
while (head) //while head is a valid node
{
s.push(head -> val); //push the val data into a stack
head = head -> next; //update head node
}
while (!s.empty())
{
c.push_back(s.top()); //take the top data of stack
s.pop(); //pop the top data
}
return c;
}
};
让思维见见世面
浙公网安备 33010602011771号