循环双链表的插入删除操作--(作业)

#include<iostream>
using namespace std;

//先定义双链表
typedef struct DNode
{
    int data;
    struct DNode *prior,*next; //prior 指向前一个结点,next指向后一个节点。
}DNode,*DoubleLIst;

//先初始化循环双链表
void inisDoublelist(DoubleLIst *L)
{
    *L = (DNode *)malloc(sizeof(DNode));
    //创建头节点
    (*L)->prior = (*L)->next = (*L);
}

//尾插法创建数据
void insertheadtail(DoubleLIst L,int n)
{
    DNode *p = L , *q; //创建中间变量
    while(n--)
    {
        q=(DNode *)malloc(sizeof(DNode)); 
        scanf("%d",&q->data);
        p->next=q;
        q->prior=p;
        p = q;
    }
    p->next=L; //达到循环的效果
}

//插入操作
int DlinkIns(DNode* L,int i,int a)
{
    DNode *s,*p;
    if(i<=0) return false;
    s=L;
    while(i--)
    {
        s=s->next;
    }
    p=s;
    s=(DNode*)malloc(sizeof(DNode));
    if(s)
    {
        s->data=a;
        s->prior=p->prior;
        p->prior->next=s;
        s->next=p;
        p->prior=s;
        return true;
    }
    else return false;
}

//输出链表
void printList(DoubleLIst L)
{
    DoubleLIst p = L->next;
    while(p!=L)
    {
        printf("%d ",p->data);
        p=p->next;
    }
    printf("\n");
}

//删除操作
int DlinkDel(DNode *L,int i)
{
    DNode *s,*p;
    if(i<=0) return false;
    s=L;
    while(i--)
    {
        s=s->next;
    }
    p=s;
    p->prior->next=p->next;
    p->next->prior=p->prior;
    free(p);
    system("pause");
    return true;
}

int main()
{
    int n,i;
    DNode *L;
    inisDoublelist(&L);
    scanf("%d",&n);
    insertheadtail(L,n);
    printList(L);
    printf("请输入要插入的位置i,和要插入的数n\n");
    cin>>i>>n;
    DlinkIns(L,i,n);
    printList(L);
    printf("请输入要删除的位置i\n");
    cin>>i;
    DlinkDel(L,i);
    printList(L);
    return 0;
}

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值