题目描述
输入一个链表,从尾到头打印链表每个节点的值。
思路:
1.Vector在头部插入
1 递归思想
2 利用栈的后进先出
我对数据结构这里的链表记得不是太清楚了。
1.
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> value;
while(head!=NULL)
{
value.insert(value.begin(),head->val);
head=head->next;
}
return value;
}
};
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> value;
while(head!=NULL)
{
value.insert(value.begin(),head->val);
head=head->next;
}
return value;
}
};
2.
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> value;
if(head!=NULL)
{
if(head->next!=NULL)
{ printListFromTailToHead(head->next);}
value.push_back(head->val);
}
return value;
}
};
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> value;
if(head!=NULL)
{
if(head->next!=NULL)
{ printListFromTailToHead(head->next);}
value.push_back(head->val);
}
return value;
}
};
这里编译未通过所有测试用例,比对一下辨认的代码,做了修改
printListFromTailToHead(head->next);修改
Value=printListFromTailToHead(head->next);
思考了一下,原因在于之前函数的结果未赋值给value,因此,就只有最后一次运行的值了。
3.
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
stack<int> sta;
vector<int> value;
while(head!=NULL)
{
sta.push(head->val);
head=head->next;
}
while(!sta.empty())
{
int a=sta.top();
sta.pop();
value.push_back(a);
}
return value;
}
};
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
stack<int> sta;
vector<int> value;
while(head!=NULL)
{
sta.push(head->val);
head=head->next;
}
while(!sta.empty())
{
int a=sta.top();
sta.pop();
value.push_back(a);
}
return value;
}
};
一、先看一下链表的概念
链表是一种动态数据结构,特点:一组任意的存储单元(既可以连续也可以不连续)存放数据元素。
二、链表元素
链表中每一个元素称为“结点”,每个结点都是由数据域和指针域组成,指针域指向下一个结点。Head是头指针,用来指向第一个结点,最后一个结点的指针域为NULL(空地址),代表链表的结束。
实际上,每个结点可以有若干个数据域和指针域。结点中只有一个指针的链表称为单链表。