首页 > 其他 > 详细

链表反转

时间:2020-09-04 15:54:38      阅读:47      评论:0      收藏:0      [点我收藏+]


#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <climits>
#include <deque>

using namespace std;


struct Node{
    int val;
    Node *next;

    Node(int x):val(x),next(NULL){}
};


class LinkedList{
private:
    Node *root;
    Node *head;

public:
    LinkedList(){
        root = new Node(0);
        head = root;
    }

    void build_list(vector<int> arr){
        for(auto item:arr){
            Node *new_node = new Node(item);
            root->next = new_node;
            root = root->next;
        }
    }


    Node *get_head(){
        return head->next;
    }

};


void print_List(Node *node){
    while(node){
        cout<<node->val<<" ";
        node = node->next;
    }
}

Node *reverse_list(Node *root){
    Node *first_node=NULL;
    Node *second_node=NULL;

    while(root){
        second_node = root->next;
        root->next = first_node;
        first_node = root;
        root = second_node;
    }

    return first_node;
}


int main(int argc, char const *argv[]){

    vector<int> arr={1,2,3,4,5,6,7,8,9};

    LinkedList list;
    list.build_list(arr);
    Node *head = list.get_head();
    print_List(head);

    cout<<endl;
    print_List(reverse_list(head));


    return 0;
}

链表反转

原文:https://www.cnblogs.com/zhouyc/p/13614235.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!