回归数据结构(4):双向循环链表

双向循环链表的插入,删除的操作如图:
这里写图片描述

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>

typedef struct LNode{
    int data;
    struct LNode *next;
    struct LNode *prior;
}Node,*LinkList;

int createLinkList(LinkList &L,int length){
    LinkList head,temp,hmove ;
    L = (LinkList)malloc(sizeof(Node));
    if(!L){
        printf("malloc action error");
        return 0;
    }
    L->next = L;
    L->prior = L;
    hmove = head = L;
    int j=0;

    for(;j<length;j++){
        temp = (LinkList)malloc(sizeof(Node));
        if(!temp){
           printf("malloc action error");
           return 0;
        }
        scanf("%d",&temp->data);
        temp->next = head;
        head->prior = temp;
        temp->prior = hmove;
        hmove->next = temp;
        hmove = temp;
    }
    return 1;
}
int printLinkList(LinkList L){
    LinkList head;
    head = L;
    head = head->next;
    while(head!=L){
        printf("%d ",head->data);
        head = head->next;
    }
    return 1;
}
int insertLinkList(LinkList L,int i,int element){
    LinkList head,temp;
    head = L;
    head = head->next;
    int j = 0;
    while(j<i-1){
        ++j;
        head = head->next;
        if(head == L){
            break;
        }
    }
    if(j<i-1){
        printf("insert  ERROR");
        return 0;
    }
    temp = (LinkList)malloc(sizeof(Node));
        if(!temp){
           printf("malloc action error");
           return 0;
        }
    temp->data = element;
    temp->next = head->next;
    temp->prior =head;
    head->next = temp;
    temp->next->prior = temp;
    return 1;
}
int deleteLinkList(LinkList L,int i){
    LinkList head;
    int j =0;
    head = L;
    head = head->next;
    while(j<i-1){
        ++j;
        head = head->next;
        if(head==L){
            break;
        }
    }
     if(j<i-1){
        printf("insert  ERROR");
        return 0;
    }
    printf("%d\n",head->data);
    head->prior->next = head->next;
    head->next->prior = head->prior;
    free(head);
    return 1;
}
int main(){
    LinkList L;
    int length;
    printf("create linkList\n");
    scanf("%d",&length);
    createLinkList(L,length);
    printLinkList(L);

    //
    printf("\ninsert linkList\n");
    int index,element;
    scanf("%d%d",&index,&element);
    insertLinkList(L,index,element);
    printLinkList(L);

    printf("\ndelete linkList\n");
    scanf("%d",&index);
    deleteLinkList(L,index);
    printLinkList(L);


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值