0% found this document useful (0 votes)
6 views

Module 4 Stack

Uploaded by

Bhubon Mondal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Module 4 Stack

Uploaded by

Bhubon Mondal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Review Questions

1. What do you understand by stack overflow and underflow?


2. Differentiate between an array and a stack.
3. How does a stack implemented using a linked list differ from a stack implemented using
an array?
4. Differentiate between peek () and pop() functions.
5. Why are parentheses not required in postfix/prefix expressions?
6. Explain how stacks are used in a non-recursive program?
7. What do you understand by a multiple stack? How is it useful?
8. Explain the terms infix expression, prefix expression, and postfix expression. Convert the
following infix expressions to their postfix equivalents:
(a) A-B+C
(b) A*B+C/D
(c) (A-B)+C*D/E-C
(d) (A*B) + (C/D) - (D+E)
(e) (A-B)+D/(E+F)*G)
(f) (A - 2*B+C)/D*E)+F
(g) 14/7%3-4+9/2
9. Convert the following infix expressions to their postfix equivalents:
(a) A-B+C
(b) A*B+C/D
(c) (A-B)+C*D/E-C
(d) (A*B)+(C/D)-(D+E)
(e) (A-B)+D/(E+F)*G))
(f) (A-2*B+C)/D*E)+F
(g) 14/7%3-4+9/2
10. Find the infix equivalents of the following postfix equivalents:
(a) AB+C*D- (b) ABC*+D-
11. Give the infix expression of the following prefix expressions.
a. *-+ABCD b. +-a*BCD
12. Convert the expression given below into its corresponding postfix expression and then
evaluate it. Also write a program to evaluate a postfix expression.
10 +((7—5)+ 10)/2
13. Write a function that accepts two stacks. Copy the contents of the first stack in the
second stack. Note that the order of elements must be preserved. (Hint: use a temporary
stack)
14. Draw the stack structure in each case when the following
operations are performed on an empty stack.
(a) Add A,B,C.D,E,F
(b) Delete two letters
(c) Add G
(d) Add H
(e) Delete four letters
(f) Add I
15. Differentiate between an iterative function and a recursive function. Which one will you
prefer to use and in what circumstances? Explain the Tower of Hanoi problem.
16. Explain the Tower of Hanoi problem.
Answers

1. What do you understand by stack overflow and underflow?

● Stack Overflow occurs when there is no more space to push new elements onto the
stack because it has exceeded its capacity. This happens when the stack reaches its
maximum limit.
● Stack Underflow happens when there is an attempt to pop an element from an empty
stack, which doesn't have any elements to remove.

2. Differentiate between an array and a stack.


Feature Array Stack

Structure A linear data structure. A linear data structure, but follows LIFO
(Last In, First Out) principle.

Insertion/Deletion Can insert or delete at any Can only insert (push) at the top and
position. remove (pop) from the top.

Access Allows random access to Access is restricted to only the top


elements. element.

Size Fixed or dynamic based on Typically, fixed size or dynamic, but


implementation. controlled by the system.

3. How does a stack implemented using a linked list differ from a stack
implemented using an array?

● Stack using Linked List:


○ The size is dynamic (can grow as long as memory allows).
○ Memory allocation is done at runtime.
○ No need to predefine size.
○ Can lead to memory overhead due to pointer storage.
● Stack using Array:
○ The size is fixed and must be predefined.
○ Faster access to elements due to contiguous memory.
○ If the stack grows beyond the predefined size, it may lead to stack overflow.
○ Memory is allocated statically or dynamically with a fixed upper limit.

4. Differentiate between peek() and pop() functions.

● peek(): This function returns the top element of the stack without removing it.
● pop(): This function removes and returns the top element of the stack.

5. Why are parentheses not required in postfix/prefix expressions?

In postfix and prefix expressions, the order of operations is already defined due
to the position of operators relative to operands. The placement of operators in these
expressions ensures that the operations are carried out in the correct order, making
parentheses unnecessary.

6. Explain how stacks are used in a non-recursive program.

Stacks are used in non-recursive programs to simulate the function call stack manually.
For example, when solving problems like tree traversals, expression evaluation, or
depth-first search, a stack can be used to store intermediate states instead of relying on
recursion.

7. What do you understand by a multiple stack? How is it useful?

A multiple stack refers to having multiple stacks within a single data structure, such as
a fixed-size array or memory block. It's useful when you want to manage multiple
collections of data (stacks) but need to use a single contiguous memory space. This is
typically implemented by dividing a memory block into segments for each stack.

8. Explain the terms infix expression, prefix expression, and postfix


expression. Convert the following infix expressions to their postfix
equivalents.

● Infix Expression: Operators are placed between operands (e.g., A + B).


● Prefix Expression: Operators are placed before their operands (e.g., +AB).
● Postfix Expression: Operators are placed after their operands (e.g., AB+).

Conversion to Postfix:

(a) A - B + C → A B - C +

(b) A * B + C / D → A B * C D / +

(c) (A - B) + C * D / E - C → A B - C D * E / + C -

(d) (A * B) + (C / D) - (D + E) → A B * C D / + D E + -

(e) (A - B) + D / (E + F) * G → A B - D E F + / G * +

(f) (A - 2 * B + C) / D * E + F → A 2 B * - C + D / E * F +

(g) 14 / 7 % 3 - 4 + 9 / 2 → 14 7 / 3 % 4 - 9 2 / +

9. Convert the following infix expressions to their postfix equivalents:

(a) A - B + C → A B - C +

(b) A * B + C / D → A B * C D / +

(c) (A - B) + C * D / E - C → A B - C D * E / + C -

(d) (A * B) + (C / D) - (D + E) → A B * C D / + D E + -

(e) (A - B) + D / (E + F) * G → A B - D E F + / G * +

(f) (A - 2 * B + C) / D * E + F → A 2 B * - C + D / E * F +

(g) 14 / 7 % 3 - 4 + 9 / 2 → 14 7 / 3 % 4 - 9 2 / +

10. Find the infix equivalents of the following postfix expressions:

(a) AB + C * D - → (A + B) * C - D

(b) ABC * + D - → A + (B * C) - D

11. Give the infix expression of the following prefix expressions.

(a) *-+ABCD
○ Infix Expression: (A + B) * (C - D)

(b) +-a*BCD

○ Infix Expression: a + (B * C) - D

12. Convert the expression given below into its corresponding postfix
expression and then evaluate it. Also, write a program to evaluate a postfix
expression.

Expression: 10 + ((7 - 5) + 10) / 2

Postfix Expression:
10 7 5 - 10 + 2 / +

Evaluation:

1. 10 7 5 - → 7 - 5 = 2 → 10 2 10 + 2 / +
2. 10 2 10 + → 2 + 10 = 12 → 10 12 2 / +
3. 10 12 2 / → 12 / 2 = 6 → 10 6 +
4. 10 6 + → 10 + 6 = 16

Result: 16

Program to evaluate a postfix expression:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define MAX 50

int stack[MAX];
int top = -1;

void push(int val) {


if (top == MAX - 1) {
printf("Stack Overflow\n");
} else {
stack[++top] = val;
}
}

int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
} else {
return stack[top--];
}
}

int evaluatePostfix(char* expression) {


for (int i = 0; i < strlen(expression); i++) {
if (isdigit(expression[i])) {
push(expression[i] - '0'); // Convert char to int
} else {
int val2 = pop();
int val1 = pop();
switch (expression[i]) {
case '+': push(val1 + val2); break;
case '-': push(val1 - val2); break;
case '*': push(val1 * val2); break;
case '/': push(val1 / val2); break;
}
}
}
return pop();
}

int main() {
char expression[] = "10 7 5 - 10 + 2 / +";
printf("Result: %d\n", evaluatePostfix(expression));
return 0;
}
13. Write a function that accepts two stacks. Copy the contents of the first
stack in the second stack. Note that the order of elements must be
preserved. (Hint: use a temporary stack)
#include <stdio.h>
#include <stdlib.h>

#define MAX 50

int stack1[MAX], stack2[MAX], temp[MAX];


int top1 = -1, top2 = -1, topTemp = -1;

void push(int stack[], int* top, int val) {


stack[++(*top)] = val;
}

int pop(int stack[], int* top) {


return stack[(*top)--];
}

void copyStack(int stack1[], int* top1, int stack2[], int*


top2) {
while (*top1 != -1) {
int val = pop(stack1, top1);
push(temp, &topTemp, val);
}
while (topTemp != -1) {
int val = pop(temp, &topTemp);
push(stack2, top2, val);
}
}

void displayStack(int stack[], int top) {


for (int i = 0; i <= top; i++) {
printf("%d ", stack[i]);
}
printf("\n");
}
int main() {
push(stack1, &top1, 10);
push(stack1, &top1, 20);
push(stack1, &top1, 30);

printf("Stack 1: ");
displayStack(stack1, top1);

copyStack(stack1, &top1, stack2, &top2);

printf("Stack 2 (copied): ");


displayStack(stack2, top2);

return 0;
}

14. Draw the stack structure in each case when the following operations are
performed on an empty stack.

(a) Add A, B, C, D, E, F
Stack after each operation:

Push A → [A]
Push B → [A, B]
Push C → [A, B, C]
Push D → [A, B, C, D]
Push E → [A, B, C, D, E]
Push F → [A, B, C, D, E, F]

(b) Delete two letters


After two pops:

Pop → [A, B, C, D, E]
Pop → [A, B, C, D]

(c) Add G
Push G → [A, B, C, D, G]
(d) Add H
Push H → [A, B, C, D, G, H]

(e) Delete four letters


Pop four times → [A]

(f) Add I
Push I → [A, I]

15. Differentiate between an iterative function and a recursive function.


Which one will you prefer to use and in what circumstances?
Feature Iterative Function Recursive Function

Definition Uses loops (for, while) for Calls itself to solve a problem.
repeated execution.

Memory Uses constant memory for Uses memory for each function call,
Usage execution. leading to a stack overflow risk.

Performance Generally more efficient, avoids Can be slower due to function call
overhead of multiple function overhead.
calls.

When to Use Preferred when the problem can Preferred when the problem is naturally
be easily solved using loops. recursive (e.g., tree traversals,
factorials).

16. Explain the Tower of Hanoi problem.

The Tower of Hanoi is a classic problem in computer science that involves three rods
and a number of disks of different sizes. The objective is to move all disks from the
source rod to the target rod, following these rules:

1. Only one disk can be moved at a time.


2. Each move consists of taking the top disk from one stack and placing it on
another stack.
3. No disk may be placed on top of a smaller disk.

Solution: This problem is solved recursively:

● Move n-1 disks from the source rod to the auxiliary rod.
● Move the nth disk to the target rod.
● Move n-1 disks from the auxiliary rod to the target rod.

The minimum number of moves required to solve the Tower of Hanoi problem is 2^n -
1, where n is the number of disks.

Programming Exercises
1. Write a program to implement a stack using a linked list.
2. Write a program to convert the expression “a+b” into “ab+".
3. Write a program to convert the expression “a+b” into “+ab”.
4. Write a program to implement a stack that stores names of students in the class.
5. Write a program to input two stacks and compare their contents.
Answers

1. Create a Stack Using Linked List


#include <stdio.h>
#include <stdlib.h>

typedef struct Node {


int data;
struct Node* next;
} Node;

Node* top = NULL;

void push(int value) {


Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = top;
top = newNode;
}

int pop() {
if (!top) return -1;
Node* temp = top;
int value = temp->data;
top = top->next;
free(temp);
return value;
}
int main() {
push(10); push(20);
printf("Popped: %d\n", pop());
return 0;
}

2. Convert "a+b" to "ab+"


#include <stdio.h>

int main() {
char infix[] = "a+b", postfix[4];
postfix[0] = infix[0];
postfix[1] = infix[2];
postfix[2] = infix[1];
postfix[3] = '\0';
printf("Postfix: %s\n", postfix);
return 0;
}

3. Convert "a+b" to "+ab"


#include <stdio.h>

int main() {
char infix[] = "a+b", prefix[4];
prefix[0] = infix[1];
prefix[1] = infix[0];
prefix[2] = infix[2];
prefix[3] = '\0';
printf("Prefix: %s\n", prefix);
return 0;
}

4. Stack Storing Names of Students


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Node {


char name[50];
struct Node* next;
} Node;

Node* top = NULL;

void push(char* name) {


Node* newNode = (Node*)malloc(sizeof(Node));
strcpy(newNode->name, name);
newNode->next = top;
top = newNode;
}

int main() {
push("Alice"); push("Bob");
printf("Top: %s\n", top->name);
}

5. Compare Two Stacks


#include <stdio.h>
#include <stdlib.h>

typedef struct Node {


int data;
struct Node* next;
} Node;

int compare(Node* s1, Node* s2) {


while (s1 && s2 && s1->data == s2->data) {
s1 = s1->next; s2 = s2->next;
}
return (s1 == NULL && s2 == NULL);
}

int main() {
Node *s1 = NULL, *s2 = NULL;
printf("Stacks are %s\n", compare(s1, s2) ? "equal" : "not
equal");
return 0;
}

Stack using Array:


1. Write a program to insert an element into the stack using an array (Push Operation).
2. Write a program to delete an element from the stack using an array (Pop Operation).
3. Write a program to return the value of the topmost element of the stack (without deleting
it from the stack) using an array (Peep operation).
4. Write a program to display the elements of a
stack using an array.
Answers

1. Push Operation (Insert Element into Stack)


#include <stdio.h>
#define SIZE 5

int stack[SIZE], top = -1;

void push(int value) {


if (top == SIZE - 1) {
printf("Stack Overflow\n");
return;
}
stack[++top] = value;
printf("%d pushed to stack\n", value);
}

int main() {
push(10);
push(20); }
2. Pop Operation (Delete Element from Stack)
#include <stdio.h>
#define SIZE 5

int stack[SIZE], top = -1;

void push(int value) {


if (top == SIZE - 1) return;
stack[++top] = value;
}

int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
}
return stack[top--];
}

int main() {
push(10); push(20);
printf("Popped: %d\n", pop());
return 0;
}

3. Peep Operation (Return Topmost Element Without Deleting)


#include <stdio.h>
#define SIZE 5

int stack[SIZE], top = -1;

void push(int value) {


if (top == SIZE - 1) return;
stack[++top] = value;
}
int peep() {
if (top == -1) {
printf("Stack is empty\n");
return -1;
}
return stack[top];
}

int main() {
push(10); push(20);
printf("Topmost element: %d\n", peep());
return 0;
}

4. Display Stack Elements


#include <stdio.h>
#define SIZE 5

int stack[SIZE], top = -1;

void push(int value) {


if (top == SIZE - 1) return;
stack[++top] = value;
}

void display() {
if (top == -1) {
printf("Stack is empty\n");
return;
}
for (int i = top; i >= 0; i--)
printf("%d ", stack[i]);
printf("\n");
}

int main() {
push(10); push(20); push(30);
printf("Stack: ");
display();
return 0;
}

Stack using Linked List:


1. Write a program to insert an element into the stack using linked list (Push
Operation).
2. Write a program to delete an element from the stack using linked list (Pop
Operation).
3. Write a program to return the value of the topmost element of the stack
(without deleting it from the stack) using linked list (Peep operation).
4. Write a program to display the elements of a stack using linked list .
Answers

1. Push Operation (Insert Element into Stack Using Linked List)


#include <stdio.h>
#include <stdlib.h>

typedef struct Node {


int data;
struct Node* next;
} Node;

Node* top = NULL;

void push(int value) {


Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = top;
top = newNode;
printf("%d pushed to stack\n", value);
}

int main() {
push(10);
push(20); }
2. Pop Operation (Delete Element from Stack Using Linked List)
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {


int data;
struct Node* next;
} Node;

Node* top = NULL;

void push(int value) {


Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = top;
top = newNode;
}

int pop() {
if (!top) {
printf("Stack Underflow\n");
return -1;
}
Node* temp = top;
int value = temp->data;
top = top->next;
free(temp);
return value;
}

int main() {
push(10); push(20);
printf("Popped: %d\n", pop());
return 0;
}
3. Peep Operation (Return Topmost Element Without Deleting)
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {


int data;
struct Node* next;
} Node;

Node* top = NULL;

void push(int value) {


Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = top;
top = newNode;
}

int peep() {
if (!top) {
printf("Stack is empty\n");
return -1;
}
return top->data;
}

int main() {
push(10); push(20);
printf("Topmost element: %d\n", peep());
}

4. Display Stack Elements Using Linked List


#include <stdio.h>
#include <stdlib.h>

typedef struct Node {


int data;
struct Node* next;
} Node;

Node* top = NULL;

void push(int value) {


Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = top;
top = newNode;
}

void display() {
if (!top) {
printf("Stack is empty\n");
return;
}
Node* temp = top;
while (temp) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}

int main() {
push(10); push(20); push(30);
printf("Stack: ");
display();
return 0;
}

You might also like