DS_双向链表C++实现

//如题所示

// DS_DoublyLinkedList.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
using namespace std;

template<class T>
class DBLNode
{
public:
	T data;
	DBLNode<T> *prior, *next;
};

template<class T>
class DBLinkList
{
public:
	int num;

	DBLinkList() { head = NULL; num = 0; }
	void initN();
	DBLNode<T> searchN(int i);
	bool insertN(int i, T e);
	bool deleteN(int i);
	void printL();
private:
	DBLNode<T> *head;
};

int main()
{
	DBLinkList<double> dbList;
	dbList.initN();
	dbList.insertN(1, 1);
	dbList.insertN(2, 2);
	dbList.insertN(3, 3);
	dbList.insertN(4, 4);
	dbList.printL();
	dbList.insertN(9, 9);

	dbList.deleteN(1);
	dbList.printL();

	dbList.deleteN(9);

	system("pause");
    return 0;
}

template<class T>
void DBLinkList<T>::initN()
{
	head = new DBLNode<T>;
	if (!head) { cerr << "fail to allocate place " << endl; exit(1); }
	head->next = head->prior = head;
}

template<class T>
DBLNode<T> DBLinkList<T>::searchN(int i)
{
	return DBLNode<T>();
}

template<class T>
bool DBLinkList<T>::insertN(int i, T e)
{
	if (num + 1 < i) { cerr << "fault, exceed bound " << endl; return false; }

	DBLNode<T> *p = new DBLNode<T>;
	p->data = e;
	int j = 1;
	DBLNode<T> *before = head, *after = head->next;
	while (i != j)
	{
		++j;
		before = before->next;
		after = after->next;
	}
	p->prior = before;
	p->next = after;
	before->next = p;
	after->prior = p;
	++num;

	return true;
}

template<class T>
bool DBLinkList<T>::deleteN(int i)
{
	if (num < i) { cerr << "fault, exceed bound " << endl; return false; }

	int j = 1;
	DBLNode<T> *me = head->next;
	while (i != j)
	{
		++j;
		me = me->next;
	}
	me->prior->next = me->next;
	me->next->prior = me->prior;
	delete(me);
	--num;

	return true;
}

template<class T>
void DBLinkList<T>::printL()
{
	if (head->prior == head->next)
		cout << "It's empty" << endl;
	DBLNode<T> *me = head->next;
	int j = 1;
	while (j <= num)
	{
		cout << me->data << " ";
		me = me->next;
		++j;
	}
	cout << endl;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值