单向循环链表操作

文章目录


前言

单循环链表顾名思义,它是一个循环链接的表,当我们把单链表的尾节点指向头节点时,就形成了一个循环,此时就是一个单循环链表。


代码

单链表的增、删、查。

// 单循环链表:指针指向头节点

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

// 链表构造
typedef struct Node
{
    int data;
    struct Node* next;
}Node;

// 初始化
Node* initList()
{
    // 开辟空间,创建节点
    Node* ptr = (Node*)malloc(sizeof(Node));
    ptr->data = 0;
    ptr->next = ptr;//自己指向自己
}

// 头插法
void headInsert(Node* list, int data)
{
    // 开辟空间,创建节点
    Node* node = (Node*)malloc(sizeof(Node));
    node->data =data;//传数据

    node->next = list->next;//让新建节点指向头节点
    list->next = node;//头节点指向新建节点
    list->data++;//头节点data用来记录后面节点数量
}

// 尾插法
void tailInsert(Node* list, int data)
{
    // 开辟空间,创建节点
    Node* node = (Node*)malloc(sizeof(Node));
    node->data = data;//传数据
    node->next = list;//指向头节点

    // 找到最后一个节点,在最后一个节点后面插入
    Node* current = list->next;//第一个节点,从此节点开始遍历
    while (current->next != list)//最后一个节点的特点:它的next为头节点
    {
        current=current->next;//移动到下一个节点
    }

    current->next = node;//原尾节点指向新的尾节点
    list->data++;//节点数量+1
}

// 删除操作
void delete(Node* list, int data)
{
    Node* pre = list;//用来移动节点的前一个节点
    Node* current = list->next;//第一个节点,用来移动
    while (current != list)
    {
        if (current->data == data)//匹配到相应节点
        {
            pre->next = current->next;//让前一个节点指向相应节点的后续节点
            free(current);//释放相应节点
            current = NULL;
            list->data--;//节点数量-1
            printf("删除成功!\n");
            return;
        }
        pre = current;//不匹配往后移动
        current = current->next;
    }
    printf("没找到!\n");
}




// 打印链表
void printList(Node* list)
{
    Node* current = list->next;//current指向第一个节点
    // 从第一个节点开始遍历
    while (current != list)//直到遇到头节点才停止遍历
    {
        printf("%d->", current->data);
        current = current->next;
    }
    printf("NULL\n");
}

int main(int argc, char const *argv[])
{
    // 单链表初始化
    Node* list = initList();
    headInsert(list, 1);
    headInsert(list, 2);
    headInsert(list, 3);
    headInsert(list, 4);
    headInsert(list, 5);
    printList(list);

    tailInsert(list, 6);
    tailInsert(list, 7);
    tailInsert(list, 8);
    tailInsert(list, 9);
    tailInsert(list, 10);
    printList(list);

    delete(list, 4);
    delete(list, 10);
    // delete(list, 11);
    printList(list);
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值