C语言创建一个单链表并要求能够实现查找、插入、删除、打印基本操作,链表数据由键盘读入
时间: 2024-09-26 12:05:08 浏览: 32
C语言实现带头结点的链表的创建、查找、插入、删除操作
在C语言中,创建一个单链表通常会涉及以下几个步骤:
1. 定义链表节点结构体(Node):
```c
typedef struct Node {
int data; // 存储数据域
struct Node* next; // 指向下一个节点的指针
} Node;
```
2. 创建链表头结点:
```c
Node* head = NULL;
```
3. 插入操作:
- 首先检查链表是否为空,然后依次插入元素。
```c
void insert(int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = head;
if (head != NULL)
head->prev = newNode;
head = newNode;
}
```
4. 查找操作:
- 使用当前节点遍历链表直到找到目标值或到达末尾。
```c
Node* search(int target) {
Node* current = head;
while (current != NULL && current->data != target) {
current = current->next;
}
return current;
}
```
5. 删除操作:
- 找到要删除的节点,并更新前一个节点指向下一个节点,如果删除的是头节点,还需特殊处理。
```c
void delete(int target) {
Node* current = head;
Node* previous = NULL;
if (current != NULL && current->data == target) {
head = current->next;
free(current);
return;
}
while (current != NULL && current->data != target) {
previous = current;
current = current->next;
}
if (current != NULL)
previous->next = current->next;
free(current);
}
```
6. 打印链表:
```c
void printList() {
Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
```
阅读全文