使用c语言编写一个单链表代码,实现其基本运算并删除值相同的多余结点、按序插入
时间: 2024-09-23 10:06:29 浏览: 53
在C语言中,我们可以创建一个简单的单链表结构,并实现添加、删除和排序功能。这里是一个基础的示例,包括链表节点结构、初始化链表、添加元素、删除重复值以及插入有序元素:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建一个新的链表节点
Node* create_node(int data) {
Node* new_node = (Node*)malloc(sizeof(Node));
if (!new_node) {
printf("Memory allocation failed.\n");
return NULL;
}
new_node->data = data;
new_node->next = NULL;
return new_node;
}
// 添加元素到链表
void add_to_list(Node** head, int data) {
Node* newNode = create_node(data);
if (*head == NULL) {
*head = newNode;
} else {
Node* curr = *head;
while (curr->next != NULL && curr->next->data != data) {
curr = curr->next;
}
if (curr->next == NULL || data < curr->next->data) {
newNode->next = *head;
*head = newNode;
} else {
curr->next = newNode;
}
}
}
// 删除重复值
void remove_duplicates(Node** head) {
if (*head == NULL) {
return;
}
Node* current = *head;
Node* runner = *head;
while (current->next != NULL) {
if (current->data == runner->data) {
runner->next = current->next;
} else {
runner = runner->next;
}
current = current->next;
}
}
// 插入有序值
void insert_sorted(Node** head, int data) {
if (*head == NULL || data <= (*head)->data) {
add_to_list(head, data);
} else {
Node* curr = *head;
while (curr->next != NULL && data > curr->next->data) {
curr = curr->next;
}
add_to_list(&curr->next, data);
}
}
// 打印链表
void print_list(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int main() {
Node* head = NULL;
// 初始化并添加一些元素
add_to_list(&head, 5);
add_to_list(&head, 2);
add_to_list(&head, 8);
add_to_list(&head, 2); // 含有重复值
printf("Original list: ");
print_list(head);
// 删除重复值
remove_duplicates(&head);
printf("\nList after removing duplicates: ");
print_list(head);
// 插入有序值
insert_sorted(&head, 3);
insert_sorted(&head, 6);
insert_sorted(&head, 4); // 非递增顺序插入
printf("\nList after inserting sorted elements: ");
print_list(head);
return 0;
}
```
阅读全文