单向循环链表(C++实现)

本文详细介绍了如何使用C++编程语言实现单向循环链表,包括链表节点的定义、插入、删除、遍历等操作,旨在帮助读者深入理解数据结构中的链表概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdio.h>
#include<stdlib.h>
#define ERROR 0
#define OK    1
typedef int ElemType;
typedef int Status;
typedef struct LNode
{
    ElemType data;
    struct LNode *next;
}LNode,*LinkList;
Status InitList_L(LinkList &L)
{
    L=(LinkList)malloc(sizeof(LNode));
    if(!L)
    return ERROR;
    L->next=L;
}
Status ClearList_L(LinkList &L)
{
    struct LNode *p,*q;
    if(L->next==L)
    return OK;
    p=L->next;
    while(p!=L)
    {
        q=p->next;
        free(p);
        p=q;
    }
    L->next=L;    
} 
Status DestroyList_L(LinkList &L) 
{
    struct LNode *p,*q;
    if(L==NULL)
    return OK;
    p=L->next;
    while(p!=L) 
    {
        q=p->next;
        free(p);
        p=q;
    }
    L->next=L;
    free(L
单向循环链表是一种特殊的链表结构,其中最后一个节点的指针指向第一个节点,形成一个环形。这种数据结构通常用于需要频繁从头开始遍历的情况,比如音乐播放列表或游戏中的队列。下面是一个简单的C++实现: ```cpp #include <iostream> // 定义节点结构体 struct Node { int data; Node* next; // 指向下一个节点的指针 }; class CircularLinkedList { private: Node* head; // 链表头部 public: // 构造函数,初始化链表为空 CircularLinkedList() : head(nullptr) {} // 添加新元素到链表尾部并连接形成循环 void addNode(int value) { if (head == nullptr) { head = new Node{value, head}; } else { Node* newNode = new Node{value, head->next}; head->next->next = newNode; head->next = newNode; } } // 打印链表所有元素(循环遍历) void display() const { if (head != nullptr) { Node* temp = head; do { std::cout << temp->data << " "; temp = temp->next; } while (temp != head); } std::cout << "\n"; } // 删除指定值的第一个节点(若存在),仅适用于非空链表 bool removeNode(int value) { if (head == nullptr || head->data != value) return false; Node* current = head; while (current->next != head) { if (current->next->data == value) { Node* toDelete = current->next; current->next = current->next->next; delete toDelete; return true; } current = current->next; } return false; // 如果找到的是头结点并且不是目标值,则链表为空或只有一个元素 } ~CircularLinkedList() { // 析构函数释放内存 Node* current = head; while (current) { Node* temp = current; current = current->next; delete temp; } head = nullptr; } }; int main() { CircularLinkedList list; list.addNode(1); list.addNode(2); list.addNode(3); list.display(); // 输出: 1 2 3 list.removeNode(2); list.display(); // 输出: 1 3 return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AHU_YZQ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值