type
status
date
slug
summary
tags
category
icon
password
URL
Below is a C++ implementation of a basic singly linked list.
The Code
Explanation
This C++ code implements a simple linked list using arrays to manage node values and pointers.
- Initialization (
initializeList
): - The
headIndex
variable keeps track of the head of the list, initially set to1
to indicate an empty list. currentIndex
is used to keep track of the next available index for new nodes.nextIndex
is an array that simulates the "next" pointers for each node. We initialize all values to1
to indicate no subsequent nodes.
- Adding Nodes:
addToHead(int value)
: Adds a new value at the beginning of the linked list. This is done by assigning the value to thevalues
array and updating the next pointer to point to the previous head.addAfter(int index, int value)
: Adds a new value after the specified index. This requires checking that the given index is valid and updating the next pointers accordingly.
- Removing Nodes:
removeAfter(int index)
: Deletes the node that comes immediately after the given index by adjusting the next pointer of the current node to skip the next node. If the next pointer is1
, it means there is no node to remove.
- Displaying the Linked List (
displayList
): - Iterates through the linked list starting from the head and prints each value. This function handles the case of an empty list by checking if
headIndex
is1
.