Linked List Basic
C
Medium
2 views
Problem Description
Create a node structure (data, next pointer). Manually create and link five nodes. Then traverse through the pointers and print them. The foundation of a linked list.
Official Solution
#include <stdio.h>
#include <stdlib.h>
/* Node structure */
struct Node {
int data;
struct Node *next;
};
int main() {
/* Create 5 nodes manually */
struct Node node1, node2, node3, node4, node5;
/* Assign data */
node1.data = 10;
node2.data = 20;
node3.data = 30;
node4.data = 40;
node5.data = 50;
/* Link nodes */
node1.next = &node2;
node2.next = &node3;
node3.next = &node4;
node4.next = &node5;
node5.next = NULL; // Last node points to NULL
/* Traverse and print the linked list */
struct Node *ptr = &node1;
printf("Linked List elements:n");
while (ptr != NULL) {
printf("%d -> ", ptr->data);
ptr = ptr->next;
}
printf("NULLn");
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!