给我一段c语言的链表代码
时间: 2023-04-10 19:03:59 浏览: 101
C语言链表代码
以下是一段简单的C语言链表代码:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void printList(struct Node* n) {
while (n != NULL) {
printf("%d ", n->data);
n = n->next;
}
}
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
printList(head);
return 0;
}
```
这段代码创建了一个简单的链表,包含三个节点,每个节点都包含一个整数和指向下一个节点的指针。主函数中创建了三个节点,然后将它们连接起来,最后通过调用printList函数打印出链表中的所有元素。
阅读全文