在C语言中用尾部插入创建单链表并且其数据从键盘上输入、求链表长度、输出链表、插入、删除和查找等功能,并且测试以上功能。
时间: 2024-09-27 13:10:37 浏览: 34
数据结构关于链表的C程序
在C语言中,我们可以使用结构体定义链表节点,然后通过头插法或尾插法来实现链表的操作。这里我们以尾插法为例,首先创建`Node`结构体:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
// 尾部插入函数
void insertAtEnd(Node** head, int value) {
if (*head == NULL) {
*head = (Node*)malloc(sizeof(Node));
(*head)->data = value;
(*head)->next = NULL;
} else {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// 获取链表长度
int getLength(Node* head) {
int length = 0;
Node* temp = head;
while (temp != NULL) {
length++;
temp = temp->next;
}
return length;
}
// 打印链表
void printList(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int main() {
Node* head = NULL;
// 输入并插入元素
int num;
while (scanf("%d", &num) != EOF) {
insertAtEnd(&head, num);
}
// 输出链表
printList(head);
// 测试其他功能
int searchValue, found = 0;
printf("Enter a value to search: ");
scanf("%d", &searchValue);
Node* current = head;
while (current != NULL && !found) {
if (current->data == searchValue) {
found = 1;
} else {
current = current->next;
}
}
if (found) {
printf("Found the value %d in the list.\n", searchValue);
} else {
printf("Value not found in the list.\n");
}
// 删除操作(这里仅做简单示例,实际应用需处理特殊情况)
printf("Enter a value to delete (if any): ");
scanf("%d", &deleteValue);
current = head;
if (current != NULL && current->data == deleteValue) {
Node* temp = head;
head = head->next;
free(temp);
} else {
while (current != NULL && current->data != deleteValue) {
current = current->next;
}
if (current != NULL) {
current->next = current->next->next;
}
}
return 0;
}
```
在这个程序中,用户可以输入值,然后链表会自动添加到尾部。之后,我们会打印链表,搜索指定的值,以及尝试删除一个值(如果存在)。注意,这个简单的版本并没有处理所有可能出现的错误情况,例如删除未找到的值。
阅读全文