问题描述:1.生成双向链表:根据给定的数组元素,生成双向链表,并返回双向链表的头结点。
2.双向链表尾部添加元素:给定一个元素,在双向链表的尾部添加一个新的元素。
3.移除元素:给定一个元素,删除双向链表中与之值相等的节点。
注意事项:链表为空(添加);链表仅有一个头结点(删除)。
代码如下:
#include <iostream>
using namespace std;
struct DoubleListNode
{
int value;
DoubleListNode *next;
DoubleListNode *piror;
};
//创建双向链表
DoubleListNode* createDoubleList(int *array, int length)
{
DoubleListNode *p,*q,*pHead;
q=pHead=new DoubleListNode();
pHead->piror=NULL;
if(length==0)
pHead==NULL;
else
{
for(int i=0;i<length;i++)
{
p=new DoubleListNode();
p->value=array[i];
q->next=p;
p->piror=q;
q=p;
//链表的值跟数组中的值顺序相反
}
q->next=NULL;
}
return pHead;
}
void AddToTail(DoubleListNode *pHead,int value)
{
DoubleListNode *p=new DoubleListNode();
p->value=value;
p->next=NULL;
p->piror=NULL;
if(pHead==NULL)
pHead=p;
else
{
DoubleListNode *p1=pHead;
while(p1->next!=NULL)
p1=p1->next;
p1->next=p;
p->piror=p1;
p->next=NULL;
}
}
void RemoveNode(DoubleListNode *pHead, int value)
{
if(pHead==NULL)
{
cout<<"没有满足条件的节点!"<<endl;
return;
}
DoubleListNode *p=pHead;
DoubleListNode *pToBeDeleted=NULL;
//如果头指针等于要删除的节点的值时,需要特殊处理
if(pHead->value==value)
{
pToBeDeleted=pHead;
if(pHead->next!=NULL)
pHead=pHead->next;
}
while(p->next!=NULL&&p->next->value!=value)
p=p->next;
if(p->next!=NULL&&p->next->value==value)
{
pToBeDeleted=p->next;
p->next->next->piror=p;
p->next=p->next->next;
}
else
cout<<"没有满足条件的节点!"<<endl;
if(pToBeDeleted!=NULL)
{
delete pToBeDeleted;
pToBeDeleted=NULL;
}
}
void PrintList(DoubleListNode *pHead)
{
if(pHead==NULL)
cout<<"链表为空"<<endl;
else
{
DoubleListNode *p=pHead;
while(p!=NULL)
{
cout<<p->value<<ends;
p=p->next;
}
}
cout<<""<<endl;
}
int main()
{
int a[7]={1,2,3,4,5,6,7};
DoubleListNode *pHead=createDoubleList(a,7);
cout<<"新生成的链表中元素为:"<<endl;
PrintList(pHead);
AddToTail(pHead,8);
cout<<"添加至尾部后链表中元素为:"<<endl;
PrintList(pHead);
RemoveNode(pHead, 4);
cout<<"移除元素后链表中元素为:"<<endl;
PrintList(pHead);
// cout << "Hello world!" << endl;
return 0;
}