数据结构(循环单链表

简介: 数据结构(循环单链表

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;
}
目录
相关文章
|
5天前
|
存储 编译器 C语言
【数据结构】C语言实现单链表万字详解(附完整运行代码)
【数据结构】C语言实现单链表万字详解(附完整运行代码)
48 0
|
5天前
|
C++
数据结构(单链表
数据结构(单链表
9 0
|
5天前
|
存储
[数据结构]单链表(从0->1)
[数据结构]单链表(从0->1)
|
5天前
|
存储
数据结构基础:一篇文章教你单链表(头插,尾插,查找,头删等的解析和代码)
数据结构基础:一篇文章教你单链表(头插,尾插,查找,头删等的解析和代码)
|
5天前
|
存储
数据结构:4、链表之单链表
数据结构:4、链表之单链表
12 0
|
5天前
|
存储 算法
单链表——“数据结构与算法”
单链表——“数据结构与算法”
|
5天前
|
算法 C语言
【算法与数据结构】 C语言实现单链表队列详解2
【算法与数据结构】 C语言实现单链表队列详解
|
5天前
|
存储 算法 C语言
【算法与数据结构】 C语言实现单链表队列详解1
【算法与数据结构】 C语言实现单链表队列详解
|
5天前
|
缓存 算法 搜索推荐
【数据结构】链表(单链表与双链表实现+原理+源码)
【数据结构】链表(单链表与双链表实现+原理+源码)
|
3天前
|
前端开发 JavaScript 算法
JavaScript 中实现常见数据结构:栈、队列与树
JavaScript 中实现常见数据结构:栈、队列与树