题目描述
输入一个链表,从尾到头打印链表每个节点的值。
时间限制:1秒 空间限制:32768K 热度指数:494076
本题知识点: 链表
思路分析(3种方法):
1. 链表倒转(其中一种方法的缺点:改变了链表的结构)。
2. 利用栈的“先进后出”,从链表头到尾入栈,然后出栈。
3. 递归的方法(缺点:长链表造成递归极深)。
1.(1)利用反转函数reverse()
每访问一个结点,将该节点的值放入容器(vector)中,最后利用reverse()函数将容器翻转。
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> v;
ListNode *p=head;
while(p!=NULL){
v.push_back(p->val);
p=p->next;
}
reverse(v.begin(),v.end());
return v;
}
};
(2)自己实现链表反转
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> vec;
ListNode *buf = head;
ListNode *pre = buf;
if(head == NULL)
return vec;
while(head->next != NULL){
buf = head->next;
head->next = buf->next;
buf->next = pre;
pre = buf;
}
while(buf){
vec.push_back(buf->val);
buf = buf->next;
}
return vec;
}
};
2.利用栈的“后进先出”思想
#include <iostream>
#include<vector>
#include<string>
#include <iterator>
#include <algorithm>
#include <stack>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> result;
stack<int> s;
ListNode* p=head;
if(p==NULL)
return result;
while(p!=NULL){
s.push(p->val);
p=p->next;
}
/* int len=s.size();
for(int i=0;i<len;i++){
result.push_back(s.top());
s.pop();
}*/
while(!s.empty()){
result.push_back(s.top());
s.pop();
}
return result;
}
};
int main() {
ListNode* head = new ListNode(-1);
ListNode* pnode1 = new ListNode(0);
head->next=pnode1;
ListNode* pnode2 = new ListNode(1);
pnode1->next = pnode2;
ListNode* pnode3 = new ListNode(2);
pnode2->next = pnode3;
pnode3->next = NULL;
Solution A;
vector<int> result;
result = A.printListFromTailToHead(head);
vector<int>::iterator v = result.begin();
while(v!= result.end()) {
cout<<*v<<endl;
++v;
}
return 0;
}
3.利用递归方法(写了主函数测试)
#include <iostream>
#include<vector>
#include<string>
#include <algorithm>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
void printListFromTailToHead(ListNode* p){
if(p!=NULL){
//vector<int> result;
//进入递归
if(p->next!=NULL){
printListFromTailToHead(p->next);
}
// 输出当前结点的值
//print("%d",pListHead->val);
cout<<p->val<<endl;
//result.push_back(pListHead->val);
//return result;
}
}
int main() {
//vector<int> v;
ListNode* head = new ListNode(-1);
ListNode* pnode1 = new ListNode(0);
head->next=pnode1;
ListNode* pnode2 = new ListNode(1);
pnode1->next = pnode2;
ListNode* pnode3 = new ListNode(2);
pnode2->next = pnode3;
pnode3->next = NULL;
printListFromTailToHead(head);
return 0;
}
参考博客:
https://www.cnblogs.com/codingmengmeng/p/5857055.html
https://www.cnblogs.com/letgo/p/5699167.html
https://www.jianshu.com/p/7dfaaa93dc9a