C++双向链表

来源:互联网 发布:linux chmod 777 目录 编辑:程序博客网 时间:2024/06/06 02:11
#include <iostream>
using namespace std;


class Node
{
int data;
Node *pre;
Node *next;
friend class LinkList;
public:
Node(){ data = 0; pre = next = NULL; }
Node(int a){ data = a; pre = next = NULL; }
};


class LinkList
{
Node *head;
Node *tail;
int size;
public:
LinkList(){ head = new Node(); tail = new Node(); head = tail; size = 0; }
void creatLinkList(int);
void addLinkList(int);
void insert(int, int);
Node *findNodeWithLocation(int);
Node *findNodeWitData(int);
int del(int, int &);
void print();
};
//找到指定位置的节点
Node *LinkList::findNodeWitData(int a)
{
Node *p = head;
int temp;
while (p)
{
temp = p->data;
if (temp == a)
return p;
else
p = p->next;
}
}
//打印
void LinkList::print()
{
Node *p = head->next;
while (p->next)
{
cout << p->data << " ";
p = p->next;
}
cout << p->data <<  endl;
}
//删除某一位置  数据存a
int LinkList::del(int pos, int &a)
{
if (pos<0 || pos>size)
{
cout << "ERROR" << endl;
return 0;
}
//删除的位置在末尾  需要置尾指针next=NULL;
else if (pos == size)
{
Node *p = tail;
a = tail->data;
Node *ptemp = tail->pre;
tail = ptemp;
tail->next = NULL;
delete p;
return a;
}
else
{
Node *p = findNodeWithLocation(pos);
a = p->data;
Node *ptemppre = p->pre;
Node *ptempnext = p->next;
ptemppre->next = ptempnext;
ptempnext->pre = ptemppre;
return a;
}
}
//找到指定位置的节点
Node *LinkList::findNodeWithLocation(int pos)
{
Node *p = head;
int i = 0;
while (p)
{
if (i == pos)
return p;
else
{
p = p->next;
i++;
}
}
}
//插入某一数据
void LinkList::insert(int pos, int a)
{
if (pos > size)
addLinkList(a);
else if (pos < 0)
cout << "ERROR" << endl;
else
{
Node *p = findNodeWithLocation(pos);
Node *pnew = new Node(a);
p->pre->next = pnew;
pnew->pre = p->pre;
pnew->next = p;
p->pre = pnew;
size++;
}
}
void LinkList::creatLinkList(int n)
{
int a;
while (n-- > 0)
{
cin >> a;
addLinkList(a);
}
}
//尾插
void LinkList::addLinkList(int a)
{
Node *ptemp = tail;
Node *pnew = new Node(a);
ptemp->next = pnew;
pnew->pre = ptemp ;
tail = pnew;
size++;
}




int main()
{
int n;
int t;
cin >> n;
//n个例子
while (n-- > 0)
{
//t个数据
cin >> t;
LinkList k;
k.creatLinkList(t);
k.insert(6, 2);
k.print();
int a;
k.del(6, a);
cout << a << endl;
k.print();
}
system("pause");
}
原创粉丝点击