C语言实现单链表

要实现单链表的功能,可以使用C语言来编写。下面是一个简单的单链表的实现示例:

“`c

#include

#include

// 定义链表节点结构体

typedef struct Node {

int data; // 数据域

struct Node *next; // 指针域,指向下一个节点

} Node;

// 初始化链表为空

void initList(Node **head) {

*head = NULL;

}

// 在链表末尾添加一个节点

void append(Node **head, int data) {

// 创建新节点

Node *newNode = (Node *)malloc(sizeof(Node));

newNode->data = data;

newNode->next = NULL;

// 如果链表为空

if (*head == NULL) {

*head = newNode;

}

else {

// 找到链表最后一个节点

Node *temp = *head;

while (temp->next != NULL) {

temp = temp->next;

}

// 将新节点加入链表末尾

temp->next = newNode;

}

}

// 打印链表的所有节点

void printList(Node *head) {

Node *temp = head;

while (temp != NULL) {

printf(“%d “, temp->data);

temp = temp->next;

}

printf(“\n”);

}

int main() {

Node *head;

initList(&head); // 初始化链表为空

// 在链表末尾添加节点

append(&head, 1);

append(&head, 2);

append(&head, 3);

// 打印链表

printList(head); // 输出: 1 2 3

return 0;

}

“`

以上是单链表的基本实现,可以通过`initList()`函数进行链表的初始化,通过`append()`函数在链表末尾添加节点,通过`printList()`函数打印链表的所有节点。在`main()`函数中演示了一个简单的使用示例。

# 回答此问题

后才能回答