C++实现循环单链表程序
循环单链表是一种数据结构,它由使用自引用结构创建的节点组成。每个节点包含两个部分,即数据和对下一个链表节点的引用。
只需要第一个链表节点的引用就可以访问整个链表。这被称为头节点。链表中的最后一个节点指向链表的头节点或第一个节点。这就是它被称为循环链表的原因。
下面是一个实现循环单链表的程序。
示例
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node *next;
};
struct Node* head = NULL;
void insert(int newdata) {
struct Node *newnode = (struct Node *)malloc(sizeof(struct Node));
struct Node *ptr = head;
newnode->data = newdata;
newnode->next = head;
if (head!= NULL) {
while (ptr->next != head)
ptr = ptr->next;
ptr->next = newnode;
} else
newnode->next = newnode;
head = newnode;
}
void display() {
struct Node* ptr;
ptr = head;
do {
cout<<ptr->data <<" ";
ptr = ptr->next;
} while(ptr != head);
}
int main() {
insert(3);
insert(1);
insert(7);
insert(2);
insert(9);
cout<<"The circular linked list is: ";
display();
return 0;
}输出
The circular linked list is: 9 2 7 1 3
在上面的程序中,结构体`Node` 构成链表节点。它包含数据和指向下一个链表节点的指针。如下所示。
struct Node {
int data;
struct Node *next;
};函数`insert()`将数据插入到链表的开头。它创建一个新的节点并将数字插入到新节点的数据字段中。如果头节点为NULL,则新节点指向自身;否则,循环链表中的最后一个节点指向新节点。然后头节点指向链表的起始位置,即新节点。如下所示。
void insert(int newdata) {
struct Node *newnode = (struct Node *)malloc(sizeof(struct Node));
struct Node *ptr = head;
newnode->data = newdata;
newnode->next = head;
if (head!= NULL) {
while (ptr->next != head)
ptr = ptr->next;
ptr->next = newnode;
} else
newnode->next = newnode;
head = newnode;
}函数`display()`显示整个链表。首先,`ptr`指向头节点。然后它不断向前移动到下一个节点,直到打印出所有节点的数据值。如下所示。
void display() {
struct Node* ptr;
ptr = head;
do {
cout<< ptr->data <<" ";
ptr = ptr->next;
} while(ptr != head);
}在`main()`函数中,首先通过调用`insert()`将各种值插入到循环链表中。然后显示链表。如下所示。
int main() {
insert(3);
insert(1);
insert(7);
insert(2);
insert(9);
cout<<"The circular linked list is: ";
display();
return 0;
}
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP