要求可以在vs2022运行设计程序创建一个单向链表,并输出链表中数据。要求:从键盘输入元素的值,并在此基础上实现元素插入、删除及按值查找的功能。
时间: 2024-02-20 15:56:30 浏览: 62
单向链表,包括创建、插入、删除等基本操作
好的,下面是实现单向链表的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct node {
ElemType data;
struct node *next;
} Node;
Node *CreateList();
void InsertNode(Node *head, ElemType data);
void DeleteNode(Node *head, ElemType data);
Node *FindNode(Node *head, ElemType data);
void PrintList(Node *head);
int main() {
Node *head = CreateList();
int choice;
ElemType data;
while (1) {
printf("\n1. Insert node\n");
printf("2. Delete node\n");
printf("3. Find node\n");
printf("4. Print list\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the value to insert: ");
scanf("%d", &data);
InsertNode(head, data);
break;
case 2:
printf("Enter the value to delete: ");
scanf("%d", &data);
DeleteNode(head, data);
break;
case 3:
printf("Enter the value to find: ");
scanf("%d", &data);
Node *found = FindNode(head, data);
if (found == NULL) {
printf("Node not found.\n");
} else {
printf("Node found: %d\n", found->data);
}
break;
case 4:
PrintList(head);
break;
case 5:
exit(0);
default:
printf("Invalid choice.\n");
}
}
return 0;
}
Node *CreateList() {
Node *head = (Node *) malloc(sizeof(Node));
head->next = NULL;
return head;
}
void InsertNode(Node *head, ElemType data) {
Node *newNode = (Node *) malloc(sizeof(Node));
newNode->data = data;
newNode->next = head->next;
head->next = newNode;
}
void DeleteNode(Node *head, ElemType data) {
Node *prev = head, *cur = head->next;
while (cur != NULL && cur->data != data) {
prev = cur;
cur = cur->next;
}
if (cur == NULL) {
printf("Node not found.\n");
} else {
prev->next = cur->next;
free(cur);
}
}
Node *FindNode(Node *head, ElemType data) {
Node *cur = head->next;
while (cur != NULL && cur->data != data) {
cur = cur->next;
}
return cur;
}
void PrintList(Node *head) {
Node *cur = head->next;
while (cur != NULL) {
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
}
```
在主函数中,我们创建了一个头结点 `head`,然后通过循环实现用户交互。用户可以选择插入、删除、查找和输出链表的操作。函数 `CreateList` 创建了一个空的链表,函数 `InsertNode` 在链表头部插入一个新结点,函数 `DeleteNode` 删除链表中指定值的结点,函数 `FindNode` 查找链表中指定值的结点,函数 `PrintList` 输出链表中的所有结点的值。
阅读全文