Linked List Code Explanation
Linked List Code Explanation
Node Struct
Explanation:
❖ Defines a struct Node which represents a node of a singly linked
list.
❖ It contains two members:
✓ data: an integer to store the data of the node.
✓ next: a pointer to the next Node in the linked list.
Function push
Explanation:
❖ This function push inserts a new node with new_data at the
beginning of the linked list.
❖ It takes a reference to Node* head (reference to pointer) and
new_data (integer value for the new node).
SW Eng 2nd Year 2nd Semester DSA(Linked List)
Function printList
Explanation:
❖ This function printList prints all elements of the linked list
starting from node (typically the head of the list).
❖ Iterates through the linked list using a while loop, printing the
data of each node.
❖ Moves node to the next node (node = node->next) in each iteration
until it reaches the end of the list (node becomes NULL).
SW Eng 2nd Year 2nd Semester DSA(Linked List)
Function main
Explanation:
❖ The main function:
✓ Declares a pointer head of type Node initialized to NULL.
✓ Calls push three times to insert values (3, 2, 1) into the
linked list (head is passed by reference to push).
✓ Prints "Created Linked List: " using cout.
✓ Calls printList to print the linked list starting from head.
✓ Returns 0 to indicate successful program execution.
2. Adding a node at the end of the linked
list
Function addNode
SW Eng 2nd Year 2nd Semester DSA(Linked List)
Explanation:
❖ This function addNode adds a new node containing value at the end
of the linked list.
❖ It takes a reference to Node* head (reference to pointer to the
head of the list) and value (integer value for the new node).
❖ Creates a new node (newNode) dynamically using new.
❖ Sets the data of newNode to value.
❖ Sets newNode's next pointer to NULL to mark it as the last node.
❖ If head is NULL (empty list), it assigns head to newNode and
returns, effectively making newNode the head of the list.
❖ If the list is not empty, it traverses the list to find the last
node (current->next == NULL) and then adds newNode as the next node
of current.
Function main
3. This program’s main function operations are the same as the
previous one!
SW Eng 2nd Year 2nd Semester DSA(Linked List)
Function addNodeAtMiddle
Explanation:
❖ When fast reaches the end of the list (or the second last node if
the list has an odd number of nodes), slow will be at the middle of
the list.
❖ Creates a new node (newNode) dynamically using new and initializes
its data with value.
❖ Inserts newNode between slow and slow->next, effectively adding it
in the middle of the list.
SW Eng 2nd Year 2nd Semester DSA(Linked List)
Function main
Explanation: