Implement Stack using Linked List
Problem​
You have a linked list and you have to implement the functionalities push and pop of stack using this given linked list. Your task is to use the class as shown in the comments in the code editor and complete the functions push() and pop() to implement a stack.
Examples:​
Example 1:
Input:
push(2)
push(3)
pop()
push(4)
pop()
Output: 3 4
Explanation:
push(2) the stack will be {2}
push(3) the stack will be {2 3}
pop() poped element will be 3,
the stack will be {2}
push(4) the stack will be {2 4}
pop() poped element will be 4
Example 2:
Input:
pop()
push(4)
push(5)
pop()
Output: -1 5
Your task:​
You are required to complete two methods push() and pop(). The push() method takes one argument, an integer 'x' to be pushed into the stack and pop() which returns an integer present at the top and popped out from the stack. If the stack is empty then return -1 from the pop() method.
- Expected Time Complexity: for both push() and pop()
- Expected Auxiliary Space: for both push() and pop()
Constraints:​
Solution​
Python​
def __init__(self):
self.head = None
def push(self, data):
new_node = StackNode(data)
new_node.next = self.head
self.head = new_node
def pop(self):
if self.head is None:
return -1
else:
ele = self.head.data
self.head = self.head.next
return ele
Java​
void push(int a) {
StackNode new_node = new StackNode(a);
new_node.next = top;
top = new_node;
}
int pop() {
if (top == null) {
return -1;
} else {
int element = top.data;
top = top.next;
return element;
}
}
C++​
void MyStack ::push(int x) {
StackNode* new_node = new StackNode(x);
new_node->next = top;
top = new_node;
}
int MyStack ::pop() {
if (top == nullptr) {
return -1;
}
else {
int element = top->data;
StackNode* temp = top;
top = top->next;
delete temp;
return element;
}
}
C​
void push(struct Stack* stack, int item) {
if (stack->top == stack->capacity - 1) {
return;
}
stack->array[++stack->top] = item;
}
int pop(struct Stack* stack) {
if (stack->top == -1) {
return -1;
}
return stack->array[stack->top--];
}
- Time Complexity: for both push() and pop()
- Auxiliary Space: for both push() and pop()