数据结构(循环单链表

发布于:2024-04-20 ⋅ 阅读:(23) ⋅ 点赞:(0)

1. 讲解:

循环链表又分为循环单链表、循环双链表。

在这里插入图片描述

2. C++代码实现:

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

using namespace std;

#define ElemType int

typedef struct LNode {
	ElemType data;
	struct LNode* next;
}LNode, * LinkList;

// 初始化
bool InitList(LinkList& L) {
	L = (LNode*)malloc(sizeof(LNode));
	if (L == NULL) return false;
	L->next = L;
	return true;
}

// 判断是否为空
bool Empty(LinkList L) {
	if (L->next == L) return true;
	else return false;
}

// 判断该节点是否为表尾节点
bool isTail(LinkList L, LNode* node) {
	if (node->next == L) return true;
	else return false;
}

int main() {
    LinkList L;

    // 初始化循环单链表
    if (!InitList(L)) {
        cout << "Initialization failed." << endl;
        return -1;
    }

    // 插入节点示例
    LNode* node1 = (LNode*)malloc(sizeof(LNode));
    node1->data = 1;
    node1->next = L->next; // 将新节点插入到头节点之后
    L->next = node1;

    LNode* node2 = (LNode*)malloc(sizeof(LNode));
    node2->data = 2;
    node2->next = L->next; // 将新节点插入到头节点之后
    L->next = node2;

    // 打印链表内容
    if (!Empty(L)) {
        LNode* temp = L->next;
        while (temp != L) {
            cout << temp->data << " ";
            temp = temp->next;
        }
        cout << endl;
    }
    else {
        cout << "The list is empty." << endl;
    }

    // 判断节点是否为尾节点
    if (isTail(L, node2)) {
        cout << "node2 is the tail node." << endl;
    }
    else {
        cout << "node2 is not the tail node." << endl;
    }

    // 判断节点是否为尾节点
    if (isTail(L, node1)) {
        cout << "node1 is the tail node." << endl;
    }
    else {
        cout << "node1 is not the tail node." << endl;
    }

    return 0;
}

小结:

关注我给大家分享更多有趣的知识,以下是个人公众号,提供 ||代码兼职|| ||代码问题求解||
添加我的公众号即可: