//如题所示
// 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;
}