Consider a stack implemented using a linked list. The following operations are performed in order:
- Push 10
- Push 20
- Pop
- Push 30
- Pop
- Pop
What is the printed output of the popped elements?
struct Node {
int data;
struct Node* next;
};
struct Node* top = NULL;
void push(int x) {
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = x;
temp->next = top;
top = temp;
}
int pop() {
if (top == NULL) return -1;
int val = top->data;
struct Node* temp = top;
top = top->next;
free(temp);
return val;
}
int main() {
push(10);
push(20);
printf("%d ", pop());
push(30);
printf("%d ", pop());
printf("%d\n", pop());
return 0;
}Remember that stack is Last-In-First-Out (LIFO). The last pushed element is popped first.
The push and pop operations follow LIFO. After pushing 10 and 20, popping returns 20. Then pushing 30 and popping returns 30. Finally, popping returns the remaining 10.
For a stack implemented using a linked list, what is the time complexity of the push and pop operations?
Think about how many nodes you need to traverse for push or pop.
Both push and pop operate only at the top node, so they take constant time O(1).
Consider this pop function for a linked list stack:
int pop() {
if (top == NULL) {
printf("Stack Underflow\n");
}
int val = top->data;
struct Node* temp = top;
top = top->next;
free(temp);
return val;
}What error will occur when pop is called on an empty stack?
Look at what happens after the if condition when top is NULL.
If top is NULL, the function prints a message but continues to access top->data which causes a segmentation fault (crash).
Given a linked list stack, the following code is executed:
push(5); push(15); push(25); pop(); push(35); pop(); pop();
What is the printed output of the popped elements?
struct Node {
int data;
struct Node* next;
};
struct Node* top = NULL;
void push(int x) {
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = x;
temp->next = top;
top = temp;
}
int pop() {
if (top == NULL) return -1;
int val = top->data;
struct Node* temp = top;
top = top->next;
free(temp);
return val;
}
int main() {
push(5);
push(15);
push(25);
printf("%d ", pop());
push(35);
printf("%d ", pop());
printf("%d\n", pop());
return 0;
}Trace the stack top after each operation carefully.
Push 5,15,25 → stack top is 25. Pop returns 25. Push 35 → top is 35. Pop returns 35. Pop returns 15.
Starting with an empty linked list stack, the following operations are performed:
push(1); push(2); pop(); push(3); push(4); pop(); pop(); push(5); push(6); pop();
What is the maximum number of nodes present in the stack at any point during these operations?
Count the stack size after each push and pop operation.
The stack sizes after each operation are: push(1)=1, push(2)=2, pop=1, push(3)=2, push(4)=3, pop=2, pop=1, push(5)=2, push(6)=3, pop=2. Maximum size is 3.
