单链表的实现一
头插
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct Node {
int data;
struct Node* next;
};
// 头插法插入节点
struct Node* insertNode(struct Node* head, int value) {
// 创建新节点
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
// 新节点指向当前头节点
newNode->next = head;
// 更新头节点为新节点
head = newNode;
return head;
}
// 打印链表
void printList(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
// 插入节点
head = insertNode(head, 3);
head = insertNode(head, 7);
head = insertNode(head, 9);
// 打印链表
printf("链表内容:");
printList(head);
return 0;
}