您的位置:首页 > 编程语言 > C语言/C++

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

2016-04-26 10:50 676 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: