Create Linked List in C: Step-by-Step
In C language, linked lists can be created by defining a structure. Here is a simple example:
#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));
if(newNode == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
int main() {
// 创建链表头指针
struct Node* head = NULL;
// 添加节点到链表
struct Node* newNode = createNode(10);
head = newNode;
newNode->next = createNode(20);
newNode = newNode->next;
newNode->next = createNode(30);
newNode = newNode->next;
// 遍历链表并打印节点的值
struct Node* current = head;
while(current != NULL) {
printf("%d ", current->data);
current = current->next;
}
return 0;
}
In the code above, a Node struct is first defined to represent a linked list node. Then, new nodes are created using the createNode() function and connected together using pointers to form a linked list. Finally, the linked list is traversed to print the value of each node.