题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
/**
*已知数据结构:
* 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> sta;
ListNode *p;
p=head;
while(p!=NULL){
sta.push(p->val);
p=p->next;
}
vector<int> a(sta.size());
for(int i=0;i<sta.size();i++){
a[i]=sta.top();
sta.pop();
}
return a;
}
};
//输入head=[1,3,2]
//输出[2,3,0]
//理想输出应该是[2,3,1]
//对比正确代码,应该是for循环的问题,但具体问题不清楚正确代码
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
stack<int> sta;
ListNode *p;
p=head;
while(p){
sta.push(p->val);
p=p->next;
}
vector<int> a(sta.size()); //或者vector<int> a;
int i=0; //然后用a.push_back()函数在a向量后面追加元素.
while(!sta.empty()){
a[i]=sta.top();
i++;
sta.pop();
}
return a;
}
};
该文讨论了如何使用栈对链表进行逆序遍历,将链表节点的值以数组形式从尾到头返回。错误代码中,问题出在for循环处理栈时,而正确代码使用了while循环和push_back()方法确保了正确的顺序。
719

被折叠的 条评论
为什么被折叠?



