首页 > 其他 > 详细

链表LinkedList

时间:2020-08-27 09:31:16      阅读:65      评论:0      收藏:0      [点我收藏+]

#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;
}

链表LinkedList

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

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