用c语言写一个程序,用数据结构建链表,要求输入一个数,如果链表有这个数,就删除这个数,没有就在链表最后加上这个数
时间: 2024-10-09 10:09:26 浏览: 25
在C语言中,我们可以创建一个单向链表来实现这个功能。首先,我们需要定义一个节点结构体,然后编写一个函数来创建链表、插入元素和删除元素。下面是一个简单的实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建新节点
Node* createNode(int data) {
Node* newNode = (Node*) malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 添加元素到链表末尾
void append(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
Node* last = *head;
while (last->next != NULL) {
last = last->next;
}
last->next = newNode;
}
// 查找并删除元素
void deleteElement(Node** head, int data) {
Node* current = *head;
Node* previous = NULL;
if (current != NULL && current->data == data) {
*head = current->next;
free(current);
return;
}
while (current != NULL && current->data != data) {
previous = current;
current = current->next;
}
if (current != NULL) {
previous->next = current->next;
free(current);
}
}
// 打印链表
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 choice, num;
do {
printf("\n1. Insert\n2. Delete\n3. Exit\nChoose an operation: ");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("Enter a number to add: ");
scanf("%d", &num);
append(&head, num);
break;
case 2:
printf("Enter a number to delete: ");
scanf("%d", &num);
deleteElement(&head, num);
break;
case 3:
printf("Exiting...\n");
break;
default:
printf("Invalid choice. Try again.\n");
break;
}
} while (choice != 3);
printf("Final linked list:\n");
printList(head);
return 0;
}
```
阅读全文