利用c语言写一段代码,对给定的循环链表,设计算法实现删除链表中所有重复的元素,写简单点,包含循环链表基本功能的实现
时间: 2024-10-16 18:22:14 浏览: 32
在C语言中,我们可以创建一个循环链表结构,并实现一个函数来删除重复的节点。这里是一个简单的示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义循环链表节点结构
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建循环链表的头结点
Node* createCircularList(int arr[], int n) {
Node* head = (Node*)malloc(sizeof(Node));
if (!head) return NULL;
head->data = arr[0];
head->next = head;
for (int i = 1; i < n; i++) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
free(head);
return NULL;
}
newNode->data = arr[i];
newNode->next = head->next;
head->next = newNode;
}
return head;
}
// 检查并删除重复节点
void removeDuplicates(Node** head) {
if (*head == NULL) return;
Node* current = *head;
while (current != *head->next) { // 避免死循环
Node* temp = current->next;
while (temp != current && temp->data == current->data) {
temp = temp->next;
}
if (temp == current) continue; // 如果找到重复节点,则跳过
Node* nextToBeDeleted = current->next;
current->next = nextToBeDeleted->next;
free(nextToBeDeleted); // 释放重复节点内存
current = current->next;
}
}
// 打印循环链表
void printCircularList(Node* head) {
Node* temp = head;
do {
printf("%d ", temp->data);
temp = temp->next;
} while (temp != head);
printf("\n");
}
int main() {
int arr[] = {1, 2, 3, 4, 4, 5, 6, 7, 7, 8};
int n = sizeof(arr) / sizeof(arr[0]);
Node* listHead = createCircularList(arr, n);
if (listHead) {
printf("Original Circular List:\n");
printCircularList(listHead);
removeDuplicates(&listHead);
printf("Circular List with No Duplicates:\n");
printCircularList(listHead);
}
return 0;
}
```
这个程序首先创建了一个循环链表,然后通过`removeDuplicates`函数删除重复项,并在最后打印结果。注意,因为是在循环链表中删除节点,所以需要特别处理避免死循环的情况。
阅读全文