从尾到头打印链表
问题:输入一个链表,从尾到头打印链表每个节点的值。
思路1:用数组依次存链表的每个节点,然后reverse这个数组。
C++
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> ret;
while (head) {
ret.push_back(head->val);
head = head->next;
}
for (int i = 0, j = ret.size() - 1; i < j; i++, j--) {
int tmp = ret[j];
ret[j] = ret[i];
ret[i] = tmp;
}
return ret;
}
};
思路2:遍历链表时用栈存储每个节点的值,然后依次弹出栈中元素并存入数组。
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
stack<int> stk;
while (head) {
stk.push(head->val);
head = head->next;
}
vector<int> ret;
while (!stk.empty()) {
int ele = stk.top(); stk.pop();
ret.push_back(ele);
}
return ret;
}
};