双向链表的创建,添加与删除

问题描述: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;
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值