c语言构建一个循环链表
时间: 2023-12-25 22:48:46 浏览: 26
循环链表是一种链表结构,其中最后一个节点的 next 指针指向第一个节点,形成一个环。下面是使用 C 语言实现循环链表的基本步骤:
1. 定义链表节点结构体:
```c
typedef struct node {
int data;
struct node *next;
} Node;
```
2. 创建链表头节点并初始化:
```c
Node *head = NULL;
head = (Node*)malloc(sizeof(Node));
head->data = 0;
head->next = head;
```
3. 插入节点到链表中:
```c
Node *newNode = NULL;
newNode = (Node*)malloc(sizeof(Node));
newNode->data = 1;
newNode->next = head->next;
head->next = newNode;
```
4. 遍历循环链表:
```c
Node *p = head->next;
while (p != head) {
printf("%d ", p->data);
p = p->next;
}
```
完整代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
int main() {
Node *head = NULL;
head = (Node*)malloc(sizeof(Node));
head->data = 0;
head->next = head;
// 插入节点到链表中
for (int i = 1; i <= 5; i++) {
Node *newNode = NULL;
newNode = (Node*)malloc(sizeof(Node));
newNode->data = i;
newNode->next = head->next;
head->next = newNode;
}
// 遍历循环链表
Node *p = head->next;
while (p != head) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return 0;
}
```