C语言-数据结构-双链表插入查找

来源:互联网 发布:seo诊断seo8 编辑:程序博客网 时间:2024/06/03 21:07
#include <stdio.h>
#include <stdlib.h>
///双链表
typedef int datatype;
typedef struct node
{
    datatype data;
    struct node *prior,*next;
}body;
body *table()
{
    int i;
    body *head,*p,*s,*end;
    printf("please input element:");
    head=(body*)malloc(sizeof(body));
    head->prior=NULL;
    head->next=NULL;
    p=head;
    for(i=0;;i++)
    {
        s=(body*)malloc(sizeof(body));
        scanf("%d",&s->data);
        p->next=s;
        s->prior=p;
        p=s;
        if(getchar()=='\n')
        break;
    }
    end=(body*)malloc(sizeof(body));
    p->next=end;
    end->prior=p;
    end->next=NULL;
    return head;
}
///输出
void output(body *head)
{
    body *p=head->next;
    while(p->next)
    {
        printf("%d ",p->data);
        p=p->next;
    }
}
///查找
body *search(body *head)
{
    int x;
    body *p=head->next;
    printf("\n请输入查找并删除的值:");
    scanf("%d",&x);
    while(p->next)
    {
        if(p->data==x)
        return p;
        else
        {
            p=p->next;
        }
    }
    printf("cannt seach");
    exit(1);
}
///删除释放
void del(body *p)
{
    p->prior->next=p->next;
    p->next->prior=p->prior;
    free(p);
}
///插入
body *insert(body *head)
{
    int j=1,index;
    body *p=head,*s;
    printf("\nplaese enter index:");
    scanf("%d",&index);
    while(p->next&&j<index)
    {
        p=p->next;
        ++j;
    }
    if(!p->next||j>index)
    {
        exit(1);
    }
    s=(body*)malloc(sizeof(body));
    printf("\n请输入插入值:");
    scanf("%d",&s->data);
    s->next=p->next;
    p->next->prior=s;
    p->next=s;
    s->prior=p;
}


int main()
{
    body *head,*q;
    head=table();
    output(head);


    q=search(head);
    del(q);
    output(head);


    printf("\n");
    insert(head);
    output(head);
    return 0;
}
原创粉丝点击