Complete code for establishing a singly linked list in the C language
Below is a complete code example in the C language for creating a singly linked list.
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
struct Node {
int data;
struct Node* next;
};
// 在链表末尾插入新节点
void insertAtEnd(struct Node** head, int newData) {
// 创建新节点
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = newData;
newNode->next = NULL;
// 如果链表为空,则将新节点作为头节点
if (*head == NULL) {
*head = newNode;
return;
}
// 遍历链表直到最后一个节点
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
// 在链表末尾插入新节点
temp->next = newNode;
}
// 打印链表的元素
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL; // 初始化头节点
// 在链表末尾插入元素
insertAtEnd(&head, 1);
insertAtEnd(&head, 2);
insertAtEnd(&head, 3);
insertAtEnd(&head, 4);
insertAtEnd(&head, 5);
// 打印链表元素
printList(head);
return 0;
}
This code first defines a linked list node structure Node, which includes a data field and a pointer next pointing to the next node.
Then, by using the insertAtEnd function, a new node is inserted at the end of the linked list. This function first creates a new node, sets the data field of the new node to newData, and sets the pointer field next of the new node to NULL.
If the linked list is empty, the new node will be set as the head node. Otherwise, traverse the linked list until the last node, and then insert the new node into the next pointer of the last node.
Finally, use the printList function to print the elements of the linked list. This function will traverse the list and print the data field of each node one by one.