双向链表

#include <iostream>
using namespace std;
struct DL
{
 int data;
 DL *prior;
 DL *next;
};
DL *Creat()
{
 cout <<"请输入要创建的元素个数"<<endl;
 int count;
 cin>>count;
 DL *p1,*p2,*head;
 head=NULL;
 for(int i=0;i<count;i++)
 {
  int u;
  cout<<"请输入要插入元素的值"<<endl;
  p1=new DL;
  cin>>u;
  p1->data=u;
  if(head==NULL)
  {
   p1->prior=0;
   head=p1;
   p2=p1;
  }
  else
  {
   p2->next=p1;
   p1->prior=p2;
   p2=p1;
  }
  p2->next=NULL;
 }
 return head;
}
DL *ADD(DL *head,int i,int j)
{
 DL *p1 ,*p2;
 p2=head;
 p1=new DL;
 p1->data=j;
 int ii=1;
 if (i-1==0)
 {
  p1->prior=head->prior;
  p1->next=head;
 }
 else
 {
  while(p2!=NULL)
  {
   if(ii==i)
   {
   p1->data=j;
   p1->prior=p2->prior;
   p2->prior->next=p1;
   p1->next=p2;
   p2->prior=p1;
   }
   ii++;
   p2=p2->next;
  }
 }
 return head;
}
DL *Delete(DL *head,int j)//j代表位置
{
 int jj=1;
 int jjj=1;
 DL * p1,*p2;
 if (j-1==0)
 {
  p1=head;
  head=p1->next;
  head->prior=0;
  delete p1;
 }
 else
 {
  //p2=new DL;
  p2=head;
  //if(p2->next==NULL)
  //{
  
  //}
  
  while(p2->next!=NULL)
  
   if(jj==j)
   {
   //p1=p2;
   p2->next->prior=p2->prior;
   p2->prior->next=p2->next;
   return head;
   //delete p1;
   //delete p2;//为什么不能写?
   }
   jj++;
   p2=p2->next;
  }
  p2->prior->next=NULL;
 }
 return head;
}
DL *Change(DL *head,int i,int j)
{
 DL *p1;
 int ii=1;
 p1=head;
 while(p1!=NULL)
 {
 if(ii==i)
 {
  p1->data=j;
  break;
 }
 ii++;
 p1=p1->next;
 }
 return head;
}
int Search(DL *head,int i)
{
 DL *p1;
 p1=head;
 int ii=1;
 int iii;
 while (p1!=NULL)
 {
  if(ii==i)
  {
   iii=p1->data;
  }
  p1=p1->next;
  ii++;
 }
 return iii;
}
void View(DL *head)
{
 for (DL *p1=head;p1!=NULL;p1=p1->next)
 {
  cout<<p1->data<<endl;
 }
}
int main()
{
 DL *head;
 head=Creat();
 cout<<"增加元素,依次输入要增加元素的位置,增加元素的值"<<endl;
 int i;
 int j;
 cin>>i>>j;
 head=ADD(head,i,j);
 View(head);
 cout<<"删除元素"<<endl;
 cout<<"输入要删除的元素的位置"<<endl;
 int k;
 cin>>k;
 head=Delete(head,k);
 View(head);
 cout<<"查找元素,请输入要查找的元素的位置"<<endl;
 int h;
 cin>>h;
 cout<<Search(head,h)<<"为元素的值"<<endl;
 View(head);
 cout<<"修改元素"<<endl;
 cout<<"请输入要修改的元素的位置和修改为的值"<<endl;
 int hj;
 cin>>hj;
 int jh;
 cin>>jh;
 head=Change(head,hj,jh);
 View(head);
 return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值