请给我一段简单的C语言实现的链表代码作示范
时间: 2024-05-08 14:16:53 浏览: 65
简单链表的C语言实现
以下是一个简单的C语言实现的链表代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct Node {
int data;
struct Node* next;
};
// 创建新的链表节点
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 插入节点到链表末尾
void insertNode(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* curr = *head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = newNode;
}
// 删除指定数据的节点
void deleteNode(struct Node** head, int data) {
struct Node* curr = *head;
struct Node* prev = NULL;
while (curr != NULL && curr->data != data) {
prev = curr;
curr = curr->next;
}
if (curr == NULL) {
printf("Node not found.\n");
return;
}
if (prev == NULL) {
*head = curr->next;
} else {
prev->next = curr->next;
}
free(curr);
}
// 遍历链表并打印节点数据
void printList(struct Node* head) {
struct Node* curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
printList(head);
deleteNode(&head, 2);
printList(head);
return 0;
}
```
以上代码实现了创建、插入、删除、遍历链表的基本操作。可以根据需要进行修改和扩展。
阅读全文