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

循环单链表的基本操作(增删改查)——C语言

程序员文章站 2022-03-24 17:53:25
...

一、定义

  • 循环单链表与链表的性质相似,只是终端结点的指针不是指向空,而是指向头结点,判断空的条件是头结点指向下一个仍然还是头结点。

二、代码
1、定义结构体

typedef struct CirList {
        datatype data;
        struct CirList* next;
}CirList;

2、创建头结点

struct CirList* CreateList() {
        struct CirList* headNode = (struct CirList*)malloc(sizeof(struct CirList));
        headNode->next = headNode;
        return headNode;
}

3、新增结点

struct CirList* CreateNode(datatype data) {
        struct CirList* newNode = (struct CirList*)malloc(sizeof(struct CirList));
        newNode->data = data;
        newNode->next = NULL;
        return newNode;
}

4、插入操作

void insertList(struct CirList *headNode, datatype data) {
        struct CirList* newNode = CreateNode(data);
        newNode->next = headNode->next;
        headNode->next = newNode;
}		//头插法

5、删除操作

void deleteList(struct CirList* headNode, datatype posdata) {
        struct CirList* posNode = headNode->next;
        struct CirList* posNodefront = headNode;
        if (posNode == headNode) {
               printf("error:NULL!");
               return;
        }
        else {
               while (posNode->data != posdata) {
                       posNodefront = posNode;
                       posNode = posNode->next;
                       if (posNode == headNode) {
                              printf("error:null!");
                              return;
                       }
               }
               posNodefront->next = posNode->next;
               free(posNode);
        }
}

6、修改操作

void amendList(struct Node* headNode, datatype posdata,datatype data) {
        struct Node* posNode = headNode->next;
        if (posNode == headNode)
               printf("error!");
        else {
               while (posNode->data != posdata) {
                       posNode = posNode->next;
                       if (posNode == headNode) {
                              printf("error!");
                              return;
                       }
               }
               posNode->data = data;
        }
}

7、打印链表

void printList(struct CirList *headNode) {
        struct CirList* pMove = headNode->next;
        if (pMove == headNode) {
               printf("error:NULL!");
               return;
        }
        else {
               while (pMove != headNode) {
                       printf("%d\t", pMove->data);
                       pMove = pMove->next;
               }
        }
        putchar('\n');
}