双向链表的创建和删除

 

#include"iostream.h"
#include"string.h"

struct Node
{
 int date;
 Node* pfront;
 Node* rear;
};

Node* create();
Node* del(Node* head, int num);
//Node* inser(Node* head, Node* ptu);
void print(Node*head);
void reverprint(Node*head);

void main()
{
 Node* p, *pel;
 p = create();
 cout<<"输出链表:"<<endl;
 print(p);
 cout<<endl<<"逆序输出:"<<endl;
 reverprint(p);

 pel = del(p,5);
 cout<<"删除结点后的链表输出:"<<endl;
 print(pel);
 cout<<endl;
}

Node* create()
{
 int data;
 Node* head, *p,*pstu;
 head = new Node;
 head->pfront = NULL;
 head->rear = NULL;
 p = head;
 cin>>data;
 while(data)
 {
  pstu = new Node;
  pstu->date  = data;
  p->pfront = pstu;
  pstu->rear = p;
  p = p->pfront ;
  cin>>data;
 }
 p->pfront = NULL;
 return head;
}

void print(Node*head)
{
 Node* p = head ->pfront;
 while(p != NULL)
 {
  cout<<p->date<<" ";
  p = p->pfront ;
 }
}

void reverprint(Node*head)
{
 Node* p = head;
 while(p->pfront != NULL)
 {
  p = p->pfront ;
 }
 while(p != NULL && p != head)
 {
  cout<<p->date<<" ";
  p = p ->rear ;
 }
 cout<<endl;
}

Node* del(Node* head, int num)
{
 Node* pt = head->pfront ;
 if(head == NULL || head->pfront == NULL)
 {
  return head;
 }
 while(pt->date != num && pt->pfront!= NULL)
 {
  pt = pt->pfront ;
 }
 if(pt->date == num)
 {
  if(pt == head)
  {
   head = pt->pfront ;
  }
  else if(pt->pfront != NULL)
  {

   pt->rear->pfront = pt->pfront ;
   pt->pfront ->rear = pt->rear ;
  }
  else
  {
   pt->rear->pfront = pt->pfront ;
  }

  delete pt;
  pt = NULL;

 }
 else
 {
  cout<<"not found"<<endl;
 }
 return head;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值