/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> a;
//方法一:递归(自底向上)
vector<int> printListFromTailToHead1(ListNode* head) {
if(head!=NULL)
{
printListFromTailToHead(head->next);
a.push_back(head->val);
}
return a;
}
//方法二:栈
vector<int> printListFromTailToHead2(ListNode* head) {
vector<int>v;
stack<int>s;
while(head)
{
s.push(head->val);
head=head->next;
}
while(s.size())
{
v.push_back(s.top());
s.pop();
}
return v;
}
//方法三:逆序
vector<int> printListFromTailToHead3(ListNode* head) {
vector<int>v;
while(head)
{
v.push_back(head->val);
head=head->next;
}
reverse(v.begin(),v.end());
return v;
}
//方法四:翻转链表1
vector<int> printListFromTailToHead4(ListNode* head) {
vector<int>v;
ListNode* p=head;
ListNode* pre=NULL;
while(p)
{
ListNode* pnext=p->next;
p->next=pre;
pre=p;
p=pnext;
}
while(pre)
{
v.push_back(pre->val);
pre=pre->next;
}
return v;
}
//方法五:翻转链表2
vector<int> printListFromTailToHead(ListNode* head) {
vector<int>v;
ListNode* ahead=new ListNode(-1);
ahead->next=head;
ListNode*p=NULL;
if(head==NULL)return v;
while(head->next)
{
p=head->next;
head->next=p->next;
p->next=ahead->next;
ahead->next=p;
}
head=ahead->next;
while(head)
{
v.push_back(head->val);
head=head->next;
}
return v;
}
};
从尾到头打印链表(含翻转链表两种方法)
最新推荐文章于 2024-08-06 17:42:20 发布