用c语言写出单链表的基本操作
时间: 2024-10-25 08:03:34 浏览: 16
在C语言中,单链表是一种基础的数据结构,它由节点组成,每个节点包含数据域和指向下一个节点的指针。以下是单链表的一些基本操作:
1. **创建节点**:
```c
typedef struct Node {
int data; // 节点存储的数据
struct Node* next; // 指向下一个节点的指针
} Node;
```
2. **初始化空链表**:
```c
Node* createList() {
return NULL; // 初始化为空指针
}
```
3. **插入元素**:
```c
void insertNode(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
```
4. **查找元素**:
```c
Node* searchNode(Node* head, int value) {
Node* current = head;
while (current != NULL && current->data != value) {
current = current->next;
}
return current;
}
```
5. **删除元素**:
```c
void deleteNode(Node** head, int value) {
if (*head == NULL) return;
if ((*head)->data == value) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Node* current = *head;
while (current->next != NULL && current->next->data != value) {
current = current->next;
}
if (current->next != NULL) {
Node* toDelete = current->next;
current->next = current->next->next;
free(toDelete);
}
}
```
6. **遍历链表**:
```c
void printList(Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
```
阅读全文