用类C语言设计算法实现循环单链表就地逆置
时间: 2023-05-25 19:05:20 浏览: 123
循环单链表指的是最后一个节点的指针指向第一个节点,而且每个节点都有一个指向下一个节点的指针。要实现循环单链表的就地逆置,可以按照以下步骤操作。
1. 定义循环单链表的节点结构体,包含数据域和指向下一个节点的指针。
```
typedef struct node {
int data;
struct node *next;
} Node;
```
2. 定义循环单链表的头节点和当前节点。
```
Node *head = NULL;
Node *current = NULL;
```
3. 创建循环单链表,向链表中插入节点。
```
for (int i = 0; i < n; i++) {
Node *newNode = malloc(sizeof(Node));
newNode->data = data[i];
newNode->next = NULL;
if (head == NULL) {
head = newNode;
current = newNode;
} else {
current->next = newNode;
current = newNode;
}
}
current->next = head;
```
4. 遍历循环单链表,将链表就地逆置。
```
Node *prev = NULL;
Node *current = head;
Node *next = head->next;
while (current != head) {
current->next = prev;
prev = current;
current = next;
next = next->next;
}
current->next = prev;
head = prev;
```
完整的代码如下:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
int main() {
int n = 5;
int data[] = {1, 2, 3, 4, 5};
Node *head = NULL;
Node *current = NULL;
for (int i = 0; i < n; i++) {
Node *newNode = malloc(sizeof(Node));
newNode->data = data[i];
newNode->next = NULL;
if (head == NULL) {
head = newNode;
current = newNode;
} else {
current->next = newNode;
current = newNode;
}
}
current->next = head;
Node *prev = NULL;
Node *current = head;
Node *next = head->next;
while (current != head) {
current->next = prev;
prev = current;
current = next;
next = next->next;
}
current->next = prev;
head = prev;
printf("Reversed circular linked list: ");
Node *temp = head;
do {
printf("%d ", temp->data);
temp = temp->next;
} while (temp != head);
return 0;
}
```
输出结果为:
```
Reversed circular linked list: 5 4 3 2 1
```
阅读全文