翻转链表
2017-01-08 22:44
204 查看
#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);
}
相关文章推荐
- 翻转链表
- 翻转链表
- 链表翻转程序
- C++循环链表中进行元素的翻转
- 链表相邻元素翻转,如a->b->c->d->e->f-g,翻转后变为:b->a->d->c->f->e->g
- 翻转部分链表
- 面试题16:翻转链表
- Reverse Linked List II 翻转链表II
- 练手小程序2.链表翻转问题
- 翻转链表查找链表的倒数第k个节点位运算加法
- 翻转链表II
- 链表的翻转
- 链表翻转。给出一个链表和一个数k,比如链表1→2→3→4→5→6,k=2,翻转后2→1→4→3→6→5。
- 面试题:题目: 链表翻转。给出一个链表和一个数k,比如链表1→2→3→4→5→6,k=2,翻转后2→1→4→3→6→5
- 单链表翻转
- PHP实现单链表翻转操作示例
- Lintcode 35.翻转链表
- 链表翻转递归实现
- java实现翻转链表
- LintCode-剑指Offer-翻转链表