从尾到头打印链表
题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
解法一:可以直接反转链表,但是这样会破坏原链表的结构,所以不推荐,直接用一个vector存储链表的值,然后进行反转输出即可。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> temp; //新建一个向量,直接顺序存下链表的值
ListNode *p=head;
while(p!=NULL){
temp.push_back(p->val);
p=p->next;
}
reverse(temp.begin(),temp.end());//将向量反转,注意reverse用法
return temp;
}
};
解法二:解决这个问题肯定要遍历链表,遍历的顺序是从头到尾,而输出却需要从尾到头,这是典型的“后进先出”结构,因此可以用栈来实现。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
void PrintListReversingly_Iteratively(ListNode* pHead)
{
stack<ListNode*> nodes;
ListNode *p = pHead;
while(p!=NULL){ //入栈
nodes.push(p);
p = p->next;
}
while(!nodes.empty()){ //出栈
p = nodes.top();
cout<<p->val<<" ";
nodes.pop();
}
cout<<endl;
}

浙公网安备 33010602011771号