5、用C++实现双链表

头文件

#include<iostream>
using namespace std;
class Node
{
private:
	int _val;
	Node* _next;
	Node* _pre;
public:
	Node(int val = int())
		:_val(val),_next(nullptr),_pre(nullptr)//初始化列表
	{
	}
	Node(const Node& src)//拷贝构造
		:_val(src._val),_next(nullptr),_pre(nullptr)//初始化列表
	{
	}
	Node& operator =(const Node &src)
	{
		if (&src == this)
		{
			return *this;
		}
		_val = src._val;
		_next = src._next;
		_pre = src._pre;
	}
	int get_val();
	void set_val(int val);
	Node* get_next();
	void set_next(Node* next);
	Node* get_pre();
	void set_pre(Node* pre);

};
class List
{
public:
	typedef Node LIST_NODE_TYPE;
	List();
	~List();
	void push_back(int val);
	void pop_back();
	void push_front(int val);
	void  pop_front();
	bool Is_empty();

	void show()
	{
		if (Is_empty())
		{
			cout << "list is empty!" << endl;
		}
		LIST_NODE_TYPE* p = _head->get_next();
		while (p!=NULL)
		{
			cout <<p->get_val()<< " ";
			p = p->get_next();
		}
	}
private:
	LIST_NODE_TYPE* _head;
	LIST_NODE_TYPE* _tail;
};

函数实现

#include"homework2(链表).h"
//函数在类内实现会被默认处理类inline类型
int Node::get_val()
{
	return _val;
}
void Node::set_val(int val)
{
	_val = val;
}
Node* Node::get_next()
{
	return _next;
}
void Node::set_next(Node* next)
{
	_next = next;
}
Node* Node::get_pre()
{
	return _pre;
}
void Node::set_pre(Node* pre)
{
	_pre = pre;
}
List::List()
{
	_head = new LIST_NODE_TYPE();
	_tail = _head;
}
List::~List()
{
	while (!Is_empty())
	{
		pop_back();
	}
	delete _head;
	_head = _tail = NULL;
}
void List::push_back(int val)
{
	LIST_NODE_TYPE* node = new LIST_NODE_TYPE(val);//new一个LIST_NODE_TYPE*类型,构造值为val
	if (Is_empty())
	{
		_head->set_next(node);
		_head->set_pre(_tail);
		_tail = node;
		_tail->set_pre(_head);
		//_tail->set_next(NULL);new构造的时候已经给过了
		return;
	}
	node->set_pre(_tail);
	//node->set_next(NULL);new构造的时候已经给过了
	_tail->set_next(node);
	_tail = node;
	return;
}
void List::pop_back()
{
	if (Is_empty())
	{
		cout << "list is empty" << endl;
		return;
	}
	_tail = _tail->get_pre();
	_tail->set_next(NULL);
}
void List::push_front(int val)
{
	LIST_NODE_TYPE* node = new LIST_NODE_TYPE(val);
	if (Is_empty())
	{
		push_back(val);
	}
	node->set_next(_head->get_next());
	node->set_pre(_head);
	_head->get_next()->set_pre(node);
	_head->set_next(node);
	return;
}
void List::pop_front()
{
	if (Is_empty())
	{
		cout << "list is empty!" << endl;
		return;
	}
	_head->set_next(_head->get_next()->get_next());
	return;
}
bool List::Is_empty()
{
	return _head == _tail;
}

测试:

int main()
{
	List p1;
	p1.push_back(10);
	p1.push_front(20);
	p1.pop_front();
	for (int i = 0; i < 10; i++)
	{
		p1.push_front(i + 10);
	}
	p1.show();
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值