A stack is a linear data structure that consists of items (data). The last item entered into the stack must come out first. This follows the Last In, First Out (LIFO) principle.
In this section, we explain the core functions implemented in the LinkedList class to manage a stack.
Description:
- Adds a new element to the top of the stack.
- The new element becomes the first node in the linked list.
Steps:
- Create a new node with the given value.
- Point the new node’s
nextreference to the current top. - Update the top pointer to the new node.
Time Complexity: O(1)
Description:
- Returns the value of the top element without removing it.
- If the stack is empty, it should return
nullor indicate an empty stack.
Steps:
- Check if the stack is empty.
- Return the value of the top node.
Time Complexity: O(1)
Description:
- Removes and returns the top element of the stack.
- If the stack is empty, it should return
nullor indicate an empty stack.
Steps:
- Check if the stack is empty.
- Store the top node’s value.
- Move the top pointer to the next node.
- Delete the old top node to free memory.
- Return the stored value.
Time Complexity: O(1)
Description:
- Prints all elements of the stack from top to bottom.
- If the stack is empty, it should print a message indicating so.
Steps:
- Start from the top node.
- Traverse the linked list, printing each node’s value.
- Stop when the last node is reached.
Time Complexity: O(n)