C++---模拟实现list

#include<iostream>
#include<assert.h>

using namespace std;

typedef int DataType;

struct ListNode
{
	ListNode *_next;
	ListNode *_prev;
	ListNode  _data;
	ListNode(DataType x)
		:_data(x)
		, _next(NULL)
		, _prev(NULL)
	{}
};

class List
{
	typedef ListNode Node;
public:
	List()
		:_head(new Node(DataType()))
	{
		_head->_next = _head;
		_head-> _prev = _head;
	}
	List(const List &l)
		:_head(new Node(DataType()))
	{
		_head-> _next = _head;
		_head -> _prev = _head;
		Node *cur = l._head-> _next;
		while(cur != l._head)
		{
			PushBack(cur-> _data);
			cur = cur->_next;
		}
	}
	List& operator=(List l)
	{
		swap(_head, l._head);
		return *this;
	}
	~List()
	{
		Node *cur = _head->_next;
		while(cur != _head)
		{
			Node *next = cur->_next;
			delete cur;
			cur=next;
		}
		delete _head;
		_head = NULL;
	}
	void PushBack(DataType x)
	{
		Node *tail = _head->_prev;
		Node *newnode = new Node(x);
		tail->_next = newnode;
		newnode->prev = tail;
		newnode->_next = _head;
		_head->_prev=newnode;
		//Insert(_head,x);
	}
	void PushFront(DataType x)
	{
		Insert(_head->_next, x);
	}
	void PopBack()
	{
		Erase(_head->_prev);
	}
	void PopFront()
	{
		Erase(_head->_next);
	}
	void Insert(Node *pos, DataType x)
	{
		assert(pos);
		Node *newnode = new Node(x);
		Node *prev = pos->_prev;
		prev->_next = newnode;
		newnode->_prev = prev;
		newnode->_next = pos;
		pos->_prev = newnode;
	}
	void Erase(Node *pos)
	{
		assert(pos != _head);
		Node *prev = pos->_prev;
		Node *next = pos->_next;
		prev->_next=next;
		next->_prerv=prev;
		delete pos;
	}
	void Print()
	{
		Node *cur = _head->_next;
		while(cur != _head)
		{
			cout << cur->_data << " ";
			cur = cur->_next;
		}
		cout << endl;
	}
private:
	Node *_head;
};

如果有什么不对的地方,可以评论告诉我,望指导!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值