#include <iostream>
#include <vector>
#include <algorithm>
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> v;
ListNode* pNode = head;
while(pNode != NULL){
v.push_back(pNode->val);
pNode = pNode->next;
}
reverse(v.begin(),v.end());
for(int i = 0;i<v.size();i++)
cout << v[i] << endl;
return v;
}
};
/*递归方式翻转链表*/
class Solution_1 {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> dev,ret;
if(head!=NULL)
{
if(head->next!=NULL)
dev=printListFromTailToHead(head->next);
dev.push_back(head->val);
}
return dev;
}
};
int main()
{
ListNode n1(10);
ListNode n2(20);
ListNode n3(30);
ListNode n4(40);
n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
Solution s;
Solution_1 s1;
s.printListFromTailTohead(&n1);
s1.printListFromTailToHead(&n1);
}
#include <vector>
#include <algorithm>
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> v;
ListNode* pNode = head;
while(pNode != NULL){
v.push_back(pNode->val);
pNode = pNode->next;
}
reverse(v.begin(),v.end());
for(int i = 0;i<v.size();i++)
cout << v[i] << endl;
return v;
}
};
/*递归方式翻转链表*/
class Solution_1 {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> dev,ret;
if(head!=NULL)
{
if(head->next!=NULL)
dev=printListFromTailToHead(head->next);
dev.push_back(head->val);
}
return dev;
}
};
int main()
{
ListNode n1(10);
ListNode n2(20);
ListNode n3(30);
ListNode n4(40);
n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
Solution s;
Solution_1 s1;
s.printListFromTailTohead(&n1);
s1.printListFromTailToHead(&n1);
}