您的位置:首页 > 其它

翻转链表

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);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: