链表反转



#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;
}
posted @ 2020-09-04 15:41  real-zhouyc  阅读(90)  评论(0编辑  收藏  举报