线性表-循环链表

这篇博客介绍了循环链表和单链表的判空方法,并提供了初始化、插入新结点以及删除指定位置结点的C语言实现。初始化循环链表时,通过判断链表是否为空创建首结点,并形成环状。插入操作支持在任意位置插入新结点,删除操作则能移除给定位置的结点。

循环链表与单链表的判空:

循环链表:head->next = head
单链表:head->next = NULL

初始化:

//  初始化循环链表
void ds_init(node **pNode)
{
    int item;
    node *temp;
    node *target;
    
    printf("输入结点的值,输入0代表结束输入\n");
    
    while(1)
    {
        scanf("%d", &item);
        fflush(stdin);
        
        if (item == 0)
        {
            return;
        }
        
        //  如果原先的链表是空表
        if ((*pNode) == NULL)
        {
            *pNode = (node*) malloc(sizeof(struct CLinkList));
            (*pNode)->data = item;
            (*pNode)->next = *pNode;
        }
        
        else
        {
            for (target = (*pNode); target->next != (*pNode); target = target->next);
            
            temp = (node*) malloc(sizeof(struct CLinkList));
            
            if(!temp)
                exit(0);
            
            temp->data = item;
            temp->next = *pNode;
            target->next = temp;
            
        }
    }
}

插入操作:

//  在第i个结点前插入结点
void ds_insert(node **pNode, int i, int item)
{
    node *temp;
    node *target;
    node *p;
    
    int j = 1;
    
    if (i == 1)
    {
        temp = (node*) malloc(sizeof(struct CLinkList));
        if(!temp)
            exit(0);
        
        temp->data = item;
        //  找到最后一个结点
        for (target = (*pNode); target->next != (*pNode); target = target->next);
        
        temp->next = *pNode;
        target->next = temp;
        *pNode = temp;
    }
    else
    {
        target = *pNode;
        for (; j < i-1; j++)
        {
            target = target->next;
        }
        
        temp = (node*)malloc(sizeof(struct CLinkList));
        
        if(!temp)
            exit(0);
        
        temp->data = item;
        p = target->next;
        target->next = temp;
        temp->next = p;
    }
}

删除操作:

//  删除第i个结点
void ds_delete(node **pNode, int i)
{
    node *temp;
    node *target;
    int j = 1;
    
    if (i == 1)
    {
        //  找到最后一个结点
        for (target = (*pNode); target->next != (*pNode); target = target->next);
        temp = *pNode;
        target->next = temp->next;
        
        free(temp);
    }
    else
    {
        target = *pNode;
        
        for (; j < i-1; ++j)
        {
            target = target->next;
        }
        temp = target->next;
        target->next = temp->next;
        free(temp);
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值