欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

双向循环链表--增删查操作

程序员文章站 2022-03-15 20:32:44
...

双向循环链表与单链表区别其实不多,对比之后就是多了几个操作步骤

#include <stdio.h>
#include <malloc.h>
typedef int Elemtype;
typedef struct LNode{
    Elemtype data;
    struct LNode *prior;
    struct LNode *next;
}LNode,*LinkList;

LinkList MCreatlist_last(LinkList head,Elemtype n)//尾插法
{
    LinkList p;
    LinkList q;//尾指针
    int i;
    head=(LinkList)malloc(sizeof(LNode));
    head->next=head;
    head->prior=head;
    q=head;
    for(i=0;i<n;i++)
    {
        p=(LinkList)malloc(sizeof(LNode));
        scanf("%d",&p->data);
        p->next=q->next;
        p->prior=q;
        q->next=p;
        q=p;
    }
    head->prior=q;
    return head;
}
void InsertList(LinkList head,int i,int e)//插入
{
    LinkList p,s;
    int j=1;
    p=head->next;
    while(p!=head&&j<i)
    {
        p=p->next;
        ++j;
    }
        s=(LinkList)malloc(sizeof(LNode));
        s->data=e;
        s->next=p->next;
        p->next=s;
        s->next->prior=s;
        s->prior=p;
       /* s->prior=p->prior;
        p->prior->next=s;
        s->next=p;
        p->prior=s;*/
      //  return head;
}

void deletelist(LinkList head,int i,int *e)//删除
{
    LinkList p,q;
    int j=1;
    p=head->next;
    while(p->next&&j<i)
    {
        p=p->next;
        j++;
    }
    //p=(LinkList)malloc(sizeof(LNode));
   // *e=p->data;
   q=p;
    p->prior->next=p->next;
    p->next->prior=p->prior;
    *e=q->data;
    free(p);
}

int Getelem(LinkList head,int i)//得到
{
    LinkList p;
    int e;
    int j=1;
    p=head->next;
    while(p&&j<i)
    {
        p=p->next;
        ++j;
    }
    if(!p->next||j>i)
        return 0;
    else{
        e=p->next->data;
        return e;
    }
}
int main()
{
    LinkList head,star;
    int i=0;
    int e;
    int get;
    head=MCreatlist_last(head,5);
   /* star=head->next;
    while(i<5)
    {
        printf("%d  ",star->data);
        star=star->next;
        ++i;
    }*/

/*InsertList(head,3,2);
     star=head->next;
    while(i<6)
    {
        printf("%d  ",star->data);
        star=star->next;
        ++i;
    }*/

    deletelist(head,3,&e);
    star=head->next;
    while(i<4)
    {
        printf("%d  ",star->data);
        star=star->next;
        ++i;
    }
    printf("\n%d\n",e);


    get=Getelem(head,3);
    printf("%d",get);

    return 0;
}