题目描述
输入一个链表,从尾到头打印链表每个节点的值。方法一:从头到尾存入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> res;
if( head == NULL )
return res;
res.push_back( head->val );
while( head->next != NULL )
{
res.push_back( head->next->val );
head = head->next;
}
int i=0;
int j=res.size()-1;
while( i<j )
{
int temp = res[i];
res[i] = res[j];
res[j] = temp;
i++;
j--;
}
return res;
}
};
方法二:使用vector的insert()功能,每次将val插入到vector的第一个位置
vec.insert(pos,elem); //在pos位置插入一个elem拷贝 pos可用vec.begin()等,elem为要插入的值
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> value;
if(head != NULL)
{
value.insert(value.begin(),head->val);
while(head->next != NULL)
{
value.insert(value.begin(),head->next->val);
head = head->next;
}
}
return value;
}
};
方法三:利用栈,先从头到尾将val压入栈,然后再一个个pop出来放入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> result;
stack<int> arr;
ListNode* p=head;
while(p!=NULL)
{
arr.push(p->val);
p=p->next;
}
int len=arr.size();
for(int i=0;i<len;i++)
{
result.push_back(arr.top());
arr.pop();
}
return result;
}
};
方法四:递归
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> vec;
printListFromTailToHead(head,vec);
return vec;
}
void printListFromTailToHead(struct ListNode* head,vector<int> &vec)
{
if(head!=nullptr)
{
if(head->next!=nullptr)
{
printListFromTailToHead(head->next,vec);
}
vec.push_back(head->val);
}
}
};