链表是一种数据结构,其中的元素通过指针链接在一起。每个元素(称为节点)包含两部分:数据和指向下一个节点的指针。
以下是一个简单的C语言链表程序,它创建了一个链表,添加了一些元素,然后打印出链表中的所有元素。
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建新节点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory error\n");
return NULL;
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 在链表末尾添加新节点
void appendNode(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
Node* last = *head;
while (last->next != NULL) {
last = last->next;
}
last->next = newNode;
}
// 打印链表
void printList(Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
int main() {
Node* head = NULL;
appendNode(&head, 1);
appendNode(&head, 2);
appendNode(&head, 3);
printList(head);
return 0;
}
```
在这个程序中,我们首先定义了一个结构体`Node`来表示链表的节点。然后,我们定义了三个函数:`createNode`用于创建新的节点,`appendNode`用于在链表的末尾添加新的节点,`printList`用于打印链表的所有元素。
在`main`函数中,我们创建了一个空的链表,然后添加了三个元素,并打印出了链表的所有元素。