Traversing this linked list involves visiting each carriage in sequence, and collecting the information they hold.
This program will demonstrate how to declare and traverse a singly linked list in C. We'll break down the code step-by-step, making it easy to understand and visualize the process.
C Program for Declaring and Traversing a Singly Linked List:
#include <stdio.h>
#include <stdlib.h>
// Structure to represent a node in the linked list
typedef struct node {
int data;
struct node* next;
} Node;
// Function to create a new node
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to declare (initialize) an empty linked list
Node* declareList() {
return NULL; // An empty list is represented by a NULL head pointer
}
// Function to traverse the linked list
void traverseList(Node* head) {
if (head == NULL) {
printf("List is empty!\n");
} else {
printf("List elements: ");
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
}
int main() {
// Declare an empty list
Node* head = declareList();
// Create some nodes
Node* node1 = createNode(10);
Node* node2 = createNode(20);
Node* node3 = createNode(30);
// Connect the nodes
node1->next = node2;
node2->next = node3;
printf("Created linked list:\n");
traverseList(head); // Should print: List elements: 10 20 30
return 0;
}
Explanation:
Node structure: Defines the building block of the list, containing data and a pointer to the next node.
createNode function: Allocates memory for a new node, initializes it with data and a NULL next pointer, and returns the new node.
declareList function: Initializes the head pointer (representing the beginning) of the list to NULL, signifying an empty list.
traverseList function: Takes the head pointer as input and iterates through the list using a while loop.
Checks for an empty list by checking if the head is NULL.
If not empty, starts from the head and prints the data of each node using a current pointer that moves to the next node in each iteration.
main function:
Declares an empty list using declareList.
Creates three nodes with data 10, 20, and 30 using createNode.
Links the nodes together by setting the next pointer of each node to the next node in the sequence.
Prints the created linked list using traverseList.
Remember: This is a basic example. You can extend it further by adding functions for inserting, deleting, searching, and more complex operations on singly linked lists.
I hope this explanation, along with the image, helps you understand the concept of declaring and traversing singly linked lists in C!
Commentaires