Which one of the following node is considered the top of the stack if the stack is implemented using the linked list?
Question: Which one of the following node is considered the top of the stack if the stack is implemented using the linked list?
The top of the stack in a linked list implementation is the head node.
The head node is the first node in the linked list. The stack operations push and pop are performed on the head node.
For example, to push a new element onto the stack, we create a new node and insert it at the beginning of the linked list, making it the new head node. To pop an element from the stack, we remove the head node from the linked list and return its value.
Here is an example of a linked list implementation of a stack:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head = None
def push(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def pop(self):
if self.head is None:
return None
data = self.head.data
self.head = self.head.next
return data
# Example usage:
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop()) # 3
print(stack.pop()) # 2
print(stack.pop()) # 1
In this example, the head node is always the top of the stack. When we push a new element onto the stack, it becomes the new head node. When we pop an element from the stack, we remove the head node.
0 Komentar
Post a Comment