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

stack questions

The document provides an overview of data structures, specifically focusing on stacks, which follow the Last In First Out (LIFO) principle. It includes definitions, operations, conditions (underflow and overflow), and examples of stack usage in real life, as well as Python functions for stack operations. Additionally, it covers exercises related to stack implementation, postfix expression evaluation, and infix to postfix conversion.

Uploaded by

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

stack questions

The document provides an overview of data structures, specifically focusing on stacks, which follow the Last In First Out (LIFO) principle. It includes definitions, operations, conditions (underflow and overflow), and examples of stack usage in real life, as well as Python functions for stack operations. Additionally, it covers exercises related to stack implementation, postfix expression evaluation, and infix to postfix conversion.

Uploaded by

gsureshkrishna
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

[1] A ____________ is a way to store, organize, or manage data in efficient and

productive manner.

Data Structure

[2] A stack is one of the following types of data structure?

a) Linear b) Dynamic c) Circular d) All of these

[3] Stack data structure is following ____________ principle.

LIFO

[4] In stack data can be inserted or deleted from ____________ only.

Top

[5] The insert operation in the stack is known as pop. (True/False)

[6] You can replace any element position in the stack. (True/False)

[7] The peek operation refers to accessing/inspecting the top element in the stack.
(True/False)

[8] A condition raise due to the stack is full is known as ___________.

a) Underflow b) Overflow c) List is full d) Completely Filled

[9] While popping the element from the stack, a condition will be raised, this condition is
known as ____________.

a) Underflow b) Overflow c) List is Empty d) Blank List

[10] Stack overflow condition is raised in ____________ operation where as Stack


underflow condition is raised in _____________ operations.

Push, Pop

[11] What do you mean by data structure? Explain your answer with a suitable
example.

Ans.: The systematic way of organizatiron,storing, accessing and retrieving data


including well-defined operations, behavior and properties is known as data structure.
Examples:
1. String – Contains sequence of characters
2. List – Contains sequence of different data types
[12] What do you mean by the LIFO structure? Support your answer with real-life
examples.
Ans.: LIFO is one of the principle to access data from a data structure. It stands for Last
In First Out. It refers to the item which is inserted last will be access frist. So the top
element will be accessed first.
Example:
1. Books in the shelf
2. Stack of coins
3. Pile of chairs
4. Bangles on woman’s wrist

[13] Enlist a few of the fields where you feel a stack is used in real life.

Ans.: The stack is used in many fields in our routine life. Some examples are:
1. Browsers History
2. Mobile Phone Call log
3. Tubewell boring machine
4. Undo and redo commands in software
[14] What are the basic operations that can be performed on the stack?

Ans.: There are two basic operations can be performed on the stack:
1. Push – Inserting an element
2. Pop – Deleting an element
[15] What are the underflow and overflow conditions?

Ans.: Underflow is the condition which occurs when stack is empty while trying to delete
elements. Overflow is the condition which occurs while inerting an element when
memory is exhausted.
[16] Write steps on how you implement stack?

Ans.: The steps are:


1. Create a stack
2. Push an element
3. Pop an element
4. Traverse/Display an element
[17] Write a python function named is_underflow() to check a stack is an
underflow.

def is_underflow(stk):
if stk==[]:

return True

else:

return False

[18] Write a function to push an element into the stack.

def push(stk,e):

stk.append(e)

top = len(stk)-1

[19] Write a python function to delete an element from the stack.

def pop_stack(stk):

if stk==[]:

return "UnderFlow"

else:

e = stk.pop()

if len(stk)==0:

top = None

else:
top = len(stk)-1

return e

[20] Write a function to display the stack elements.

def display(stk):

if stk==[]:

print("Stack is Empty")

else:

top = len(stk)-1

print(stk[top],"-Top")

for i in range(top-1,-1,-1):

print(stk[i])

[21] Write a function to inspect an element from the stack.

def peek(stk):

if stk==[]:

return "UnderFlow"

else:

top = len(stk)-1
return stk[top]

[22] Write functions AddPlayer(player) and DeletePlayer(player) in python to add


and remove a player by considering them as push and pop operations in a stack.

def AddPlayer(player):

pn=input("enter player name:")

player.append(pn)

def DeletePlayer(player):

if player==[]:

print("No player found")

else:

return player.pop()

[23] Vedika has created a dictionary containing names and marks as key-value
pairs of 5 students. Write a program, with separate user-defined functions to
perform the following operations:

1. Push the keys (name of the student) of the dictionary into a stack, where
the corresponding value (marks) is greater than 70.
2. Pop and display the content of the stack.

The dictionary should be as follows:

d={“Ramesh”:58, “Umesh”:78, “Vishal”:90, “Khushi”:60, “Ishika”:95}

Then the output will be: Umesh Vishal Ishika

def push(stk,item):
stk.append(item)

def Pop(stk):

if stk==[]:

return None

else:

return stk.pop()

stk=[]

d={"Ramesh":58, "Umesh":78, "Vishal":90, "Khushi":60, "Ishika":95}

for i in d:

if d[i]>70:

push(stk,i)

while True:

if stk!=[]:

print(Pop(stk),end=" ")

else:

break
Exercise

Question 1

State TRUE or FALSE for the following cases:


(a) Stack is a linear data structure.
(b) Stack does not follow LIFO rule.
(c) PUSH operation may result into underflow condition.
(d) In POSTFIX notation for expression, operators are placed after
operands.
Answer
(a) True
Reason — A stack is a linear data structure following the Last In, First
Out (LIFO) principle, where elements are arranged sequentially.
(b) False
Reason — A stack follows the Last In, First Out (LIFO) rule. In a stack,
the last element added is the first one to be removed from the stack.
(c) False
Reason — When attempting to remove an element (POP operation)
from an empty stack, it leads to an underflow condition, resulting in an
exception being raised.
(d) True
Reason — In POSTFIX notation for expression, operators are placed
after the corresponding operands.

Question 2(a)

Find the output of the following code:


result = 0
numberList = [10, 20, 30]
numberList.append(40)
result = result + numberList.pop()
result = result + numberList.pop()
print("Result=", result)

Answer

Output
Result= 70

Explanation

The code initializes result to 0 and creates a list [10, 20, 30]. It appends
40 to the list and then performs two pop() operations on the list, which
removes and returns the last element (40 and 30). These values are
added to result, resulting in result being 70. Finally, the code prints
"Result=" followed by the value of result, which is 70.

Question 2(b)

Find the output of the following code:


answer = []; output = ''
answer.append('T')
answer.append('A')
answer.append('M')
ch = answer.pop()
output = output + ch
ch = answer.pop()
output = output + ch
ch = answer.pop()
output = output + ch
print("Result=", output)

Answer

Output
Result= MAT

Explanation

The code initializes an empty list answer and an empty string output. It
appends the characters 'T', 'A', and 'M' to the answer list. After
appending, answer list becomes ['T', 'A', 'M'].
After that, three pop() operations are performed on answer, removing and
returning the last element each time ('M', 'A', and 'T' respectively).
These characters are concatenated to the output string. So, output string
becomes MAT which is printed as the final output.

Question 3

Write a program to reverse a string using stack.


Answer
def push(stack, item):
stack.append(item)

def pop(stack):
if stack == []:
return
return stack.pop()

def reverse(string):
n = len(string)
stack = []
for i in range(n):
push(stack, string[i])
string = ""
for i in range(n):
string += pop(stack)
return string

string = input("Enter a string: ")


print("String:", string)
reversedStr = reverse(string)
print("Reversed String:", reversedStr)

Output
Enter a string: Hello world
String: Hello world
Reversed String: dlrow olleH

Question 4

For the following arithmetic expression:


((2 + 3) * (4 / 2)) + 2
Show step-by-step process for matching parentheses using stack data
structure.
Answer
For matching parentheses, we can push in the stack for each opening
parenthesis of the expression and pop from the stack for each closing
parenthesis.
Scanning from left to right:
Empty stack => Balanced Parentheses

Question 5(a)

Evaluate following postfix expression while showing


status of stack after each operation given A = 3, B = 5, C
= 1, D = 4.
AB + C *
Answer

AB + C * = 35 + 1 *
Scanning from left to right :
Hence, AB + C * = 35 + 1 * = 8

Question 5(b)

Evaluate following postfix expression while showing


status of stack after each operation given A = 3, B = 5, C
= 1, D = 4.
AB * C / D *
Answer
AB * C / D * = 35 * / 4 *
Scanning from left to right :
Hence, AB * C / D * = 35 * / 4 * = 60

Question 6(a)

Convert the following infix notation to postfix


notation, showing stack and string contents at
each step.
A+B-C*D
Answer
Given,
A+B-C*D
Scanning from left to right :

Postfix notation of A + B - C * D = AB+CD*-

Question 6(b)

Convert the following infix notation to postfix


notation, showing stack and string contents at
each step.
A * (( C + D)/E)
Answer
Given,
A * (( C + D)/E)
Scanning from left to right:
Postfix notation of A * (( C + D)/E) = ACD+E/*

Question 7

Write a program to create a Stack for storing only


odd numbers out of all the numbers entered by the
user. Display the content of the Stack along with
the largest odd number in the Stack. (Hint. Keep
popping out the elements from stack and maintain
the largest element retrieved so far in a variable.
Repeat till Stack is empty)
Answer
def push(stack, item):
stack.append(item)

def pop(stack):
if stack == []:
return
return stack.pop()

def oddStack(num):
if num % 2 == 1:
push(stack, num)

def GetLargest(stack):
elem = pop(stack)
large = elem
while elem != None:
if large < elem:
large = elem
elem = pop(stack)
return large

n = int(input("How many numbers?"))


stack = []
for i in range(n):
number = int(input("Enter number:"))
oddStack(number)
print("Stack created is", stack)
bigNum = GetLargest(stack)
print("Largest number in stack", bigNum)

Output

How many numbers?8


Enter number:1
Enter number:2
Enter number:3
Enter number:4
Enter number:5
Enter number:6
Enter number:7
Enter number:8
Stack created is [1, 3, 5, 7]
Largest number in stack 7
1. State TRUE or FALSE for the following cases: a) Stack is a linear data structure b)
Stack does not follow LIFO rule c) PUSH operation may result into underflow
condition d) In POSTFIX notation for expression, operators are placed after
operands
2. Find the output of the following code: a) result=0 numberList=[10,20,30]
numberList.append(40) result=result+numberList.pop()
result=result+numberList.pop() print(“Result=”,result) b) answer=[]; output=''
answer.append('T') answer.append('A') answer.append('M') ch=answer.pop()
output=output+ch ch=answer.pop() output=output+ch ch=answer.pop()
output=output+ch print(“Result=”,output)

3. Write a program to reverse a string using stack.

4. For the following arithmetic expression: ((2+3)*(4/2))+2 Show step-by-step


process for matching parentheses using stack data structure.

5. Evaluate following postfix expressions while showing status of stack after each
operation given A=3, B=5, C=1, D=4 a) A B + C * b) A B * C / D *

6. Convert the following infix notations to postfix notations, showing stack and
string contents at each step. a) A + B - C * D b) A * (( C + D)/E)

7. Write a program to create a Stack for storing only odd numbers out of all the
numbers entered by the user. Display the content of the Stack along with the
largest odd number in the Stack. (Hint. Keep popping out the elements from stack
and maintain the largest element retrieved so far in a variable. Repeat till Stack is
empty)

1. TRUE or FALSE: a) Stack is a linear data structure → T


RUE b) Stack does not follow LIFO rule → FALSE c) PU
SH operation may result in an underflow condition → FA
LSE d) In POSTFIX notation for expression, operators ar
e placed after operands → TRUE
4. Matching parentheses using stack: Expression: ((2+3)*(4/2)
)+2

 Read ( , push to stack


 Read ( , push to stack

 Read 2 , ignore

 Read + , ignore
 Read 3 , ignore
 Read ) , pop from stack
 Read * , ignore
 Read ( , push to stack
 Read 4 , ignore
 Read / , ignore
 Read 2 , ignore
 Read ) , pop from stack
 Read ) , pop from stack
 Read + , ignore
 Read 2 , ignore No unmatched parentheses means the e
xpression is balanced.

5. Evaluate postfix expressions: a) A B + C * → 3 5 + 1 *


 Push 3, Push 5, Pop 5 and 3, Push (3+5), Push 1, Pop 1

and 8, Push (8*1)


 Stack: [8]

b) A B * C / D * → 3 5 * 1 / 4 *

 Push 3, Push 5, Pop 5 and 3, Push (35), Push 1, Pop 1


and 15, Push (15/1), Push 4, Pop 4 and 15, Push (154)
 Stack: [60]

6. Convert infix to postfix: a) A + B - C * D

 Output: A B + C D * -

 Stack: ['-', '*']

b) A * (( C + D)/E)
 Output: A C D + E / *

 Stack: ['*', '/']

You might also like