1.利用栈实现:
利用栈先进后出的特性,将该链表中的元素push入栈中,再pop出来,注意函数返回值类型为一个vector
1.1提交版
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> return_result;
stack<int> mystack;
ListNode *p =NULL;
p = head;
while(p!=NULL)
{
mystack.push(p->val);
p=p->next;
}
while(!mystack.empty())
{
return_result.push_back(mystack.top());
mystack.pop();
}
return return_result;
1.2完整版
#include<stdio.h>
#include<list>
#include<stack>
using namespace std;
void Rev_list(list<int> &mylist){
stack<int> mystack;
list<int>::iterator i_list = mylist.begin();
while(i_list != mylist.end())
{
mystack.push(*i_list);
i_list++;
}
while(!mystack.empty())
{
printf("%d",mystack.top());
mystack.pop();
}
}
int main(){
list<int> mylist;
for(int i=1;i<=5;i++)
{
mylist.push_back(i);
}
list<int>::iterator i_list = mylist.begin();
for(i_list = mylist.begin(); i_list != mylist.end();i_list++)
{
printf("%d",*i_list);
}
Rev_list(mylist);
return 0;
}
2.利用algorithm中的reverse函数
先遍历单链表,把所有元素都存入一个vector中,再调用reverse函数反转该vector
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> my_vector;
ListNode *p = NULL;
p = head;
while(p)
{
my_vector.push_back(p->val);
p=p->next;
}
std::reverse(my_vector.begin(),my_vector.end());
return my_vector;
}
};
3.双指针迭代
参考方法:单链表反转之双指针遍历就地反转法
双指针,递归,妖魔化的双指针
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
ListNode * pre = nullptr;
ListNode * cur = head;
while(cur!=nullptr)
{
ListNode* temp = cur->next; //因为下一步会改变该节点的值,所以先存起来
cur->next = pre; //翻转
pre = cur; //下面两行是指针位移
cur = temp;
}
vector<int> v;
while(pre!=nullptr)
{
v.push_back(pre->val);
pre=pre->next;
}
return v;
}
};