码迷,mamicode.com
首页 > 其他好文 > 详细

双链表建立和删除

时间:2015-10-23 10:04:25      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<stdlib.h>
using namespace std;
typedef struct student
{
    int data;
    struct   student*next;
    struct student *pre;
}dnode;
dnode*creat()//双链表的建立
{
    dnode *head,*p,*s;
    int x,cycle=1;
    head=new dnode;
    p=head;
    while(cycle)
    {
      printf("请输入数据\n");
      scanf("%d",&x);
      if(x<=0)
          break;
      s=new dnode;
      s->data=x;
      s->pre=p;
      p->next=s;
      p=s;

    }
    head=head->next;
    head->pre=NULL;
    p->next=NULL;
    return head;
}
dnode *del(dnode *head,int num)
{
    dnode *s,*p,*q;
    s=head;
    while(s->next!=NULL)
    {
        if(s->data==num)
        {
            if(s==head)
                {
                    head=head->next;
                    head->pre=NULL;
                    delete  s;
                    return head;
                }
            else if(s->next==NULL)
            {
                s->pre->next=NULL;
                delete s;
                 return head;
            }
             else{
            p=s->pre;
            q=s->next;
            q->pre=p;
            p->next=q;
           delete s;
             }
        }
        s=s->next;
    }
    if(s==NULL)
        printf("链表没有这个数\n");
    else
       return head;

}
void print(dnode *head)//单链表打印
{
       dnode *p=head;
         p=head;
         while(p!=NULL)
         {
           printf("%d ",p->data);
            p=p->next;
         }
         printf("\n");
}
int main()
{
    dnode *head;
    int num1,num2;
    head=creat();
    print(head);
    printf("请输入要删除的数\n");
    scanf("%d",&num1);
    head=del(head,num1);
    print(head);
    return 0;
}

 

双链表建立和删除

标签:

原文地址:http://www.cnblogs.com/cancangood/p/4903435.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!