C++ 构造双向链表的实现代码

#include<iostream.h>

using namespace std;

template<class T>
struct Node
{
	Node<T> *pre;
	T data;
	Node<T>*next;
};

template <class T>
class DoubleLinkedList
{
public:
	DoubleLinkedList()
	{
		Node<T> *q = new Node<T>;
		if(q == NULL)
		{
			 cout << "Fail to malloc the head node." << endl;
		     return;
		}
		phead = q;
		phead->pre = NULL;
		phead->data = NULL;
		phead->next = NULL;
		//
		T i;
		cout << "Please input several integer number, input ctrl+z to the end: " << endl;
		while (cin >> i)
		{
			Node<T> *p = new Node<T>;
			if(p == NULL)
			{
				cout << "Fail to malloc a new node." << endl;
				return;
			}
			p->data = i;
			q->next = p;
			p->pre = q;
			p->next = NULL;
		}
	}

	int size()
	{
		Node<T> *p = phead->next;
		int count(0);
		while(p != NULL)
		{
			count++;
			p = p->next;
		}
		return count;
	}

	void print_elements()
	{
		Node<T> *p = phead->next;
		while(p != NULL)
		{
			cout << p->data << "";
			p = p->next;
		}
		cout << endl;
	}

	void insert_element(int i, T e)
	{
		if(i <= this->size())
		{
			Node<T> *m = phead;
			for(int j = 1; j < i; j++)
			{
				m = m->next;
			}
			Node<T> *n = m->next;
			Node<T> *p = new Node<T>;
			if(p == NULL)
			{
				 cout << "Failed to malloc the node." << endl; 
			}
			m->next = p;
			p->pre = m;
			p->data = e;
			p->next = n;
			n->pre = p;
		}
		else if(i == (this->size() + 1))
		{
			Node<T>* m = phead;
			for(int j = 1; j < i; j++)
			{
				m = m->next;
			}
			Node<T> *p = new Node<T>;
			if(p == NULL)
				cout << "Failed to malloc the node." << endl;
			m->next = p;
			p->pre = m;
			p->data = e;
			p->next = NULL;

		}
		else
			cout << "Please input the position number equals or smaller than " << size()+1 << endl;
		//
	}

	void insert_element(T e)
	{
		Node<T> *m = phead;
		for(int j = 1; j <= size(); j++)
		{
			m = m->next;
		}
		Node<T> *p = new Node<T>;
		if(p == NULL)
		{
			cout << "Failed to malloc the node." << endl;
		}
		m->next = p;
		p->pre = m;
		p->data = e;
		p->next = NULL;
	}

	void delete_element(int i)
	{
		Node<T> *p = phead;
		for(int j = 0; j < i; j++)
		{
			p = p->next ;
			if(p == NULL)
			{
				 cout << "The size of the list is " << size() << " ,Please input the right number." << endl;
				return;
			}
		}
		if(p->next != NULL)
		{
			Node<T> *m = p->pre;
			Node<T> *n = p->next;
			m->next = n;
			n->pre = m;
			delete p;
		}
		else
		{
			Node<T> *m = p->pre;
			m->next = NULL;
			delete p;
		}
	}

private:
	Node<T>* phead;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值