21xrx.com
2025-07-04 21:23:34 Friday
文章检索 我的文章 写文章
C++实现循环链表代码
2023-07-06 11:37:35 深夜i     17     0
C++ 循环链表 实现 代码

循环链表是一种特殊的链表,它与普通链表的区别在于,其最后一个结点指向链表的头结点,形成了一个闭环。在循环链表中,任意结点都可以作为起点遍历整个链表。如果我们想要实现一个循环链表的数据结构,可以使用C++语言来实现。

以下是C++实现循环链表的代码示例:

#include <iostream>
using namespace std;
class Node {
public:
  int data;
  Node* next;
  Node()
    data = 0;
    next = NULL;
  
};
class CircularLinkedList {
private:
  Node* head;
public:
  CircularLinkedList()
    head = NULL;
  
  void insertAtBegin(int value) {
    Node* newNode = new Node();
    newNode->data = value;
    newNode->next = head;
    if (head == NULL)
      newNode->next = newNode;
     else {
      Node* temp = head;
      while (temp->next != head)
        temp = temp->next;
      
      temp->next = newNode;
    }
    head = newNode;
  }
  void insertAtEnd(int value) {
    Node* newNode = new Node();
    newNode->data = value;
    newNode->next = head;
    if (head == NULL)
      head = newNode;
     else {
      Node* temp = head;
      while (temp->next != head)
        temp = temp->next;
      
      temp->next = newNode;
    }
  }
  void deleteAtBegin() {
    if (head == NULL)
      cout << "The list is empty!" << endl;
      return;
    
    Node* temp = head;
    while (temp->next != head)
      temp = temp->next;
    
    if (temp == head)
      head = NULL;
     else
      temp->next = head->next;
      head = head->next;
    
    delete temp;
  }
  void deleteAtEnd() {
    if (head == NULL)
      cout << "The list is empty!" << endl;
      return;
    
    Node* temp = head;
    Node* prev = NULL;
    while (temp->next != head)
      prev = temp;
      temp = temp->next;
    
    if (prev == NULL)
      head = NULL;
     else
      prev->next = head;
    
    delete temp;
  }
  void display() {
    if (head == NULL)
      cout << "The list is empty!" << endl;
      return;
    
    Node* temp = head;
    while (temp->next != head)
      cout << temp->data << " -> ";
      temp = temp->next;
    
    cout << temp->data << endl;
  }
};
int main() {
  CircularLinkedList cl;
  cl.insertAtBegin(3);
  cl.insertAtBegin(2);
  cl.insertAtBegin(1);
  cl.insertAtEnd(4);
  cl.insertAtEnd(5);
  cout << "Initial list: ";
  cl.display();
  cl.deleteAtBegin();
  cout << "After deleting first element: ";
  cl.display();
  cl.deleteAtEnd();
  cout << "After deleting last element: ";
  cl.display();
  return 0;
}

在上面的代码中,我们首先定义了一个Node类,表示链表的结点。这个类包含一个整型数据data和一个指向下一个结点的指针next。接下来,我们定义了一个CircularLinkedList类,表示循环链表的数据结构。它包含一个指向头结点的指针head。

这个类中,我们实现了四个方法:insertAtBegin、insertAtEnd、deleteAtBegin和deleteAtEnd。insertAtBegin方法用于在链表的开始处插入一个新的结点,insertAtEnd方法用于在链表的末尾插入一个新的结点。deleteAtBegin方法用于删除链表的第一个元素,deleteAtEnd方法用于删除链表的最后一个元素。在这些方法里,我们使用了while循环来遍历链表,找到需要删除或插入的位置。

最后,我们在main函数中创建了一个CircularLinkedList对象,并调用各种方法来演示其功能。运行程序后,我们可以看到循环链表中每个元素的值,并且可以在需要时插入或删除元素。

综上所述,通过使用C++语言实现循环链表的数据结构,我们可以轻松地操作链表中的元素,使其满足我们的需求。这对于编写复杂的程序或算法非常有用。

  
  

评论区