链表LinkedList


#include <iostream>
#include <vector>

using namespace std;

struct Node{
	int val;
	Node *next;

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

class LinkedList{
private:
	Node *head;
	Node *root;
public:
	LinkedList(){head = new Node(0); root=head;}
	~LinkedList();
	void build_list_by_normal(int *p, int size);
	void build_list_by_vector(vector<int> arr);
	Node* get_head();
};


LinkedList::~LinkedList(){
	head = root->next;
	while(head){
		root = head;
		delete root;
		head = head->next;
	}
}

void LinkedList::build_list_by_normal(int *p, int size){
	for(int i=0;i<size;i++){
		Node *new_node = new Node(p[i]);
		head->next = new_node;
		head = head->next;
	}
}

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

Node* LinkedList::get_head(){
	return root->next;
}


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

int main(int argc, char const *argv[]){
	vector<int> arr={1,2,3,4,5,6};
	int p[10] = {1,2,3,4,5,6,7,8,9,10};
	LinkedList list;
	list.build_list_by_vector(arr);
	list.build_list_by_normal(p,10);
	print_list(list.get_head());
	list.~LinkedList();
	print_list(list.get_head());
	
	return 0;
}
posted @ 2020-08-27 00:13  real-zhouyc  阅读(115)  评论(0编辑  收藏  举报