线性表~双向链表~插入与删除

#include<stdio.h>

typedef struct node                      //定义结构体
{
    int data;
    struct node *next;
    struct node *prior;
}linknode,*link;

link creatList(link head)                   //创建链表
{
    link r,p;
    int x,i=1;
    r=head;
    printf("请输入第%d个元素:",i++);
    scanf("%d",&x);
    while(x!=-1)
    {
        p=(link)malloc(sizeof(linknode));
        p->data=x;
        r->next=p;
        p->prior=r;
        r=p;
        printf("请输入第%d个元素:",i++);
        scanf("%d",&x);
    }
    r->next=NULL;
    return head;
}


void printList(link head)                    //打印链表
{
    link p;
    p=head->next;
    if(p==NULL)
    {
        printf("链表为空!!!\n");
        return head;
    }
    while(p)
    {
        printf("%d ",p->data);
        p=p->next;
    }
    printf("\n");
}


int lengthList(link head)                 //求链表长度
{
    link p=head->next;
    int i=0;
    while(p)
    {
        ++i;
        p=p->next;
    }
    return i;
}

link insertList(link head,int x,int i)                   //插入链表元素
{
    link p,r;
    int j;
    r=head;
    p=(link)malloc(sizeof(linknode));
    p->data=x;
    p->next=NULL;
    p->prior=NULL;

    for(j=1;j<i;j++)
    {
        r=r->next;
    }
     if(i==lengthList(head)+1)    //如果需要插入的为表尾元素,则会出现NULL->prior情形,因此对尾元素做特殊处理。
    {
         r->next=p;
         p->prior=r;
    }
    else
    {
    p->next=r->next;
    r->next->prior=p;
    r->next=p;
    p->prior=r;
    }
    return head;
}

link deleteList(link head,int x)             //删除链表元素
{
    link p,r;
    for(p=head->next,r=head;p!=NULL;p=p->next)
    {
        if(p->data==x)
        {
            break;
        }
        r=r->next;
    }
    if(p==NULL)
    {
        printf("链表中不存在此元素!!!\n");
        return head;
    }
   else
   {
    if(p->next==NULL)              //如果需要删除的为表尾元素,则会出现NULL->prior情形,因此对表尾元素做特殊处理。
    {
        r->next=NULL;
        free(p);
        return head;
    }
    else
    {
        r->next=p->next;
        p->next->prior=r;
        free(p);
    }
   }
    return head;
}

int main()
{
    int x,i;
    link head;
    link creatList(link head);                    //创建链表
    void printList(link head);                    //打印链表
    link insertList(link head,int x,int i);       //插入链表元素
    link deleteList(link head,int x);             //删除链表元素
    int lengthList(link head);
    head = (link)malloc(sizeof(linknode));
    head = creatList(head);
    printList(head);

    printf("请输入需要插入元素的值和位置:");
    scanf("%d %d",&x,&i);
    head = insertList(head,x,i);
    printList(head);

    printf("请输入需要删除元素的值:");
    scanf("%d",&x);
    head = deleteList(head,x);
    printList(head);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/mycsdn_xm/article/details/80714713
今日推荐