C语言链表实现:创建、遍历、查找和插入
很高兴为您解答问题!下面是使用C语言编写链表的示例代码,满足您的要求:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
// 创建链表
struct Node* createLinkedList(int n) {
struct Node* head = NULL;
struct Node* temp = NULL;
struct Node* p = NULL;
for (int i = 0; i < n; i++) {
temp = (struct Node*)malloc(sizeof(struct Node));
printf("请输入第%d个元素:", i+1);
scanf("%d", &temp->data);
// 判断输入元素是否递增
if (i > 0 && temp->data <= p->data) {
printf("输入的元素不递增,请重新输入最近一次的错误数据。\n");
i--;
free(temp);
continue;
}
temp->next = NULL;
if (head == NULL) {
head = temp;
} else {
p->next = temp;
}
p = temp;
}
return head;
}
// 遍历链表
void traverseLinkedList(struct Node* head) {
printf("链表元素:");
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
// 在链表中查找元素
int searchLinkedList(struct Node* head, int x) {
while (head != NULL) {
if (head->data == x) {
return 1; // 查找成功
}
head = head->next;
}
return 0; // 查找失败
}
// 在有序链表中插入元素
void insertLinkedList(struct Node** head, int x) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = x;
newNode->next = NULL;
if (*head == NULL || x < (*head)->data) {
newNode->next = *head;
*head = newNode;
} else {
struct Node* current = *head;
while (current->next != NULL && current->next->data < x) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
int main() {
int n;
printf("请输入链表的长度:");
scanf("%d", &n);
struct Node* head = createLinkedList(n);
traverseLinkedList(head);
int searchValue;
printf("请输入要查找的元素:");
scanf("%d", &searchValue);
if (searchLinkedList(head, searchValue)) {
printf("在链表中找到了该元素!\n");
} else {
printf("在链表中未找到该元素。\n");
}
int insertValue;
printf("请输入要插入的元素:");
scanf("%d", &insertValue);
insertLinkedList(&head, insertValue);
traverseLinkedList(head);
return 0;
}
请注意,此代码是以C语言编写的,与GPT-3.5 Turbo模型无关。GPT-3.5 Turbo版本仅适用于自然语言处理任务,无法执行或编写特定语言的代码。我在示例中提供了一个简单的链表实现,满足了您的要求。希望对您有所帮助!如果您对此有任何疑问,请随时提问。
原文地址: https://www.cveoy.top/t/topic/bqAY 著作权归作者所有。请勿转载和采集!