【3】从尾到头打印链表
- 时间限制:1秒
- 空间限制:32768K
本题知识点: 链表
题目描述
输入一个链表,从尾到头打印链表每个节点的值。
输入描述:
输入为链表的表头
输出描述:
输出为需要打印的“新链表”的表头
牛客网题目链接:点击这里
方法一:用栈
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
stack<int> result1;
vector<int> result;
if(head==NULL) return result;
while(head!=NULL)
{
result1.push(head->val);
head=head->next;
}
while(!result1.empty())
{
result.push_back(result1.top());
result1.pop();
}
return result;
}
};
方法二:递归
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> result;
if(head==NULL) return result;
result.insert(result.begin(),head->val);
if(head->next!=NULL)
{
vector<int> temp;
temp=printListFromTailToHead(head->next);
result.insert(result.begin(),temp.begin(),temp.end());
}
return result;
}
};
方法三:
更改链表指针,原地逆序
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> result;
if(head==NULL) return result;
struct ListNode* pre=NULL;
struct ListNode* p=head;
while( head->next!=NULL )
{
p=p->next;
head->next=pre;
pre=head;
head=p;
}
head->next=pre;
while(head!=NULL)
{
result.push_back(head->val);
head=head->next;
}
return result;
}
};
方法四:递归 深度优先
//写法一:
//其中需要不断的创建容器数组,返回容器数组,销毁递归深处的数组
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> result;
if(head==NULL) return result;
//深度优先遍历
if(head->next!=NULL)
{
result=printListFromTailToHead(head->next);
}
result.push_back(head->val);
return result;
}
};
写法二:
不需要创建和销毁数组,但是会占用初始空间
class Solution {
vector<int> result; //一次定义
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
if(head==NULL) return result;
//深度优先遍历
if(head->next!=NULL)
{
printListFromTailToHead(head->next);
}
result.push_back(head->val);
return result;
}
};
方法五:用insert方法,
代码简洁,复杂度较高
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> result;
while(head)
{
result.insert(result.begin(),head->val);
head=head->next;
}
return result;
}
};