0% found this document useful (0 votes)
3 views4 pages

Stack

The document discusses data structures, specifically focusing on stacks and their operations such as insertion, deletion, and traversal. It explains how stacks follow the Last In First Out (LIFO) principle and provides examples of operations like push, pop, and peek. Additionally, it covers the classification of data structures and their applications in programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views4 pages

Stack

The document discusses data structures, specifically focusing on stacks and their operations such as insertion, deletion, and traversal. It explains how stacks follow the Last In First Out (LIFO) principle and provides examples of operations like push, pop, and peek. Additionally, it covers the classification of data structures and their applications in programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

of an clement from a List.

It Data Structure: Stack 115


first matching accepts one
Data Structure: Stack
D e l e t i o n

9, and is uscd to 10.


parameter

Suppose the list is as given below:


element from Operations on Stack.

5
the list. rusn : Insertion of new element (from the
(10, 15, 20,30,15, 23,34] in stack. beginning)
(a) remove() : It scarches the given clement(as a
List

and removes theefirst


parameter).

matching
List = [10, 15,20,,30, 15,23,34] element. L21Push(2)SPush(5) Push(4)
4Top
5-Top
For example: [Link](15), 2
CHAPTER
The output will be [10,20,30,15,23,341
(b) pop):It accepts the index number (optional) as Pop: Deletion of element( from the beginning) in
stack.
TOPICS COVERED and removes the element ín the list.
arguments

Data Structure: Stack List (10, 15, 20, 30,15,23,341


(2). +Pop2- Pop
For example: list. pop
element into a lList. An element will be 11. Conditíons associated with
7. Insertion of an can be The output
collection of
inserted by the following
built-in methods:
List = [10,15,30, 15, 23,34]
Stack/Queue:
to store a " Overflow condition It is a situation where we are
it is away implemented (a) Insert(0: This method accepts two argument(index.
1. Data
Structure.
structure can be If no argument is [Link] it removes the last not able to add new element due to memory full
arbitrary data.
The data element). Ifthe index ís more than the size, then
dictionary, tupie,
set etc. inserted element.
or range is overfilled with values.
end.
via the list,
of Data Structure.
it willbe inserted at the Underflow condition: It is a situation where there
2.
Classification For example: Suppose the list contains [10,15,201) Searching
Data list.
1S no element left and we still wish to remove an
as element in the element or display the list.
Structure >»>list. insert (4,30): it will add element 30 at
4th index. The new list will be [10,15,20,30). 12. Applications of Stack. Stack can be used to reverse a
Linear Binary
Word or reverse a line and it can also used in function
Static or Fxed Dynamic (6) append ) : It
will insert the new element at call routines.
Stucture Structure end of the list.
Forexample: Suppose the list contains (10,15, 20,301 COMMON INSTRUCTIONS
Questions
Non-Linear as element in the list. Assertion and Reasoning
Lingar DS DS* >>>Líst. append (45). The output will he Both Assertion (A) and Reason (R) are true and Reason (R)is the corect explanatíon of
Assertion (A)
(10,15, 20,30,45] Doh Assertion (A) and Reason (R) are true and Reason (R) is not the correct
explanation of Assertion (A)
(c) extend() : It is used to add another list at the end (c) Assertion (A) is true but Reason (R) is false
Linked Tree Graph of the existing list. (d Assertion (A) is false but Reason (R) is true
Sequential Lists* For example: list-[10, 15, 20,30,45]
List1-[23,34]
[Link](List1). SOLVED QUESTION BANK
Arrays Stacks Queues
The output will be [10, 15, 20, 30, 45, 23, 34)
3. Which of the following operations removes an item
3. Operations on Data Structure. Some of the operations 8. Stack. Stack means arranging one object over another
that are performed on data structure are as follows: and these objects are removed in reverse order of their Objective Type from the top of the stack?
arrival. The stack is called Last In First Out (LIFO) ((O) Ouestions 1Mark (a) push) (b) pop)
" Insertion (Addition of new elements in the list.) (d) None of the above
" Deletion (Removal of an element from a list.) arrangement. (c) peek)
" Traversal (Visiting elements of a list.) 1. What is a stack? Ans. (b)
" Searching (Finding an clement in the list.) (a) A linear data structure 4. Which of the following operations adds an item to
4. Linear Lists or Arrays. Alist which contains same type Push the top of the stack?
Pop
of data elements. (b) A non-linear data structure
5. Types of Lists. Single Dimensional list and
Insertion Deletion (a) push) (b) pop)
(c) A circular data structure (c) peek) (d) None of the above
N-dimensional List (2D or 3D dimensional list)
6. Creation of List. We can create list by just (d) A hierarchical data structure Ans. (a)
writing the 5. What is the name of the error that occurs when
name of the list and initialize it with values. List Ans. (a)
must
be initialized with ) (Square) brackets. List in you try to pop an item from an empty stack?
is zero indexed. python 2. Which of the following is the correct order of (a) StackOverflowError
For example: lst=[1, 2,3,4,5] / Linear List operations on a stack? (b) EmptyStackException
Note: Non-linear lists and linked lists
are not part of the syllabus.]
(a) push()’ pop) (b) pop() ’ push) (c) ArayndexOutOfBoundsException

(c) peek() ’ pop) (d) push()’ peek() (d) NullPointerException


Ans. (d) Ans. (b)
Data Structure: Stack 117
( y t h o n ) - 1 2

Assertion:
Stacks are uscd in the List [Link]() 25. Python program to generate groups of 6 consecutive

hgeda
af
Computer
Science

commonly
usedto
i m p l e m e n t
15.
recursion.

Reasoning: When a function calls


mplcmelta List [int(x) for x in List]
print (List)
numbers in a list. |FileName:ch-datas\Q191
116 is
structure new stack frame. print(type(List)) Ans. 1 [[6°1 +j forjin range (1,7) ]for i in range(6)]
data
6.
Which
In this case, we can cnter the ist clcments scercoated print(1)
a stack?
(b) Queue
Ans, (a)
(a) Linked List with space. i.c 26. Write a Python program to accept the list from the
(d) Set user and print the odd position elements of the list.
(c) Tree of Short Answer Input:
complexity
Enter the list: 12345 [FileName:ch-datas\Q20]
Ans. (a) is the time Type Questions 2/3 Marks
Ans. lst-evai(input ("Enter the list"))
implemented

following
the a stack Output:
Which of on
7. pop)
operations

16. Define data


structure.
[1, 2, 3, 4, 5] prínt (1st[::2])
push)and
using a list? (6) O(log n) Ans. It is a waytO store a collection of related <class 'list> 27. Write a python program using list to print the sum
of allthe elements. (FileName:ch-datas\Q21]
(a) O(1)
(d) O(n log n) The data structure can
be
implemented Case 3:
(c) O(n) dictionary, tuple, set etc. List1-[] Ans. def sum _líst(items):
returns the top more = y SUM 0
Ans. (a)
17. Name some applications of Stack
operations
following while more=='y' 0I MOre=-'Y':
of the removing it?
for x 1n ítems:
8. Which
stack without Stack are: num=eval(input("Enter a number: "))
item ofthe (b) pop) Ans. Application of
above [Link] (num) return SUn
(a) push)
(d) None of the (a) Reverse of a String or Line. more=input ("Enter mOre data(y/n)? ") Ist=eval (input ("Enter the 1líst"))
(c) peck)
(6) Function call routines. print (List1) print (sum_list (1st) )
Ans. (c) a
following
statements is true about (c) Backtracking print (type(List1))
9. Which of the In this case, we can enter the list of items one by one Long Answer
stack?
(First In First Out) principle. 18. Alist contains LST=[10,7,9,15,12],. 8is added tu and add the element to the list using the append method. Type Questions 5 Marks
(a) It follows the FIFO principle. list. What will be the output? If
In First Out) i.e.
28. Write a program to implement the stack using list.
(6) It follows the LIFO (Last adding or removing (a) LST as Stack (b) LST as Queue Input:
for
(c) It has no specific order Ans. (a) LST as Stack Enter a number: 1 (File Name:ch-dataslQ36]
items.
LST = (8,10,7,9, 15,12] Enter more data(y/n)? y Ans. s-[I
(d) t can contain duplicate items. Enter a number: 4 c="y"
Ans. (b) (6) LST as Queue Enter more data(yn)? n while (C=="y'):
not suitable
10. Which of the following data structures is LST = [10,7,9,15,12,8] Output:
print("1. PUSH\n2. POP \n3. Display")
for implementing a stack? choice=int (input("Enter your choice: "))
(a) Linked List (b) Aray 19. Alist contains LST=[10,7,9,15,12]. An elema [1,4] if (choice--1):
removed. What will be the output? If <class 'list>
(c) Queue (d) Tree a=input("Enter any nunber :)
(a) LST as Stack (6) LST as Queue 21. Python program to check whether the list is empty [Link](a)
Ans. (c)
or not. [FileName:ch-datas\Q15] elif (choice==2):
11. Assertion: Stacks are also known as Last-In-First-Out Ans. (a) LST as Stack Ans. A = [] if (se=(]):
(LIFO) data structures. LST = (7,9,15, 12] if not A: print ("Stack Empty")
Reasoning: The item that is added last to the stack is (0) LST as QueueOC print ("List is empty") else:
the first item to be removed from the stack. print ("Deleted element is : ,[Link]())
LST = [10,7,9,15] 22. Python program to get the difference between the elif (choice=-3) :
Ans. (a) two lists. [FileName:ch-datas\Q16]
12. Assertion: Astack can only be accessed from one 20. With the help of the program, explain the dia l=len(s)
end. ways to accept the elements of the list and dis Ans. list1 = (1, 2, 3, 4] for i in range(1-1, -1, -1):
Reasoning: This property of stacks is known as its linear all the elements. [FileName:ch-datas list2 = [1, 2] print (s[i])
nature.
Ans. (a) Ans. Case 1: print (list (set (listl1) - set(list2) )) else:
print("WrOng Input")
13. Assertion: The push lst=eval(input("Enter the list")) 23. Python program to find the index of an item in a C=input("Do you want to continue or not? ")
operation in a stack adds an item specified list. (FileName:ch-datas\Q17]
to the top of the stack. print (1st) 29. Write a menu driven program in python to implement
Reasoning: The pop operation in a print(type (1st) ) Ans. num =[11, 3, 14, -8] the various method related to insertion and deletion
item from the bottom of the stack removes an In this case, while entering the Iist, we have toenla print (numn. index (3) ) (FileName:ch-dataslQ38)
stack. in the list.
Ans. (b) list in square bracket. 24. Write the algorithm for the bubble sort.
Ans. "lnsertion and Deletion""
14. Assertion: The peek operation in Input: Ans. N = len(A) se]
value of the topmost item a stack returns the for in range(1,N): #for N-1 passes
it in the stack
without removing Enter the list[1,2,3,4] for j in range (0,N-i):
c="y"
while (c=="y"):
Reasoning: This operation is also Output: aollol if (A(i] > A[j+1]) print("1. Insert\n2. Delete \n3. Display")
A[j), A[j+1] A[j+1],A[3)
operation known as the pop [1, 2, 3, 4]
Ans. (c) <class 'list>
Case 2:
(Python-12

Science
Book. append (name)
Computer
e def pop(Book):
118
Tagtker
choice: ")}) Data Structure: Stack 119
your
choice-int(input("Enter

at
if Book== ): # main
if (choicez1): end\n 2.
Insert
print ("Under Flow") Enp=(] [Link] (N)
Insert at the Players=[)
print("1.
value") while True:
Index else: P=['AMAR', 'GAGAN', "KAMAL
particular choice")) nrint("\n1. Push\n2. Pop \n3. Display\ JATIN' 'LALAN' ]
the (input('Enter
your print("Book Deleted",Book. pop) n4. Exit") for i in range(0, len(P),2):
n=int
if n=l: for
insertion:")
def display (Book) : ch=int(input("Enter your choice") push(Players, P[i])
any number
a-input("Enter
if Book=z[): if ch==1: prínt (Players)
S. append(a)
print ("Underflow! !!") push(Emp)
elif n==2: insertion:") 35. Write a function pop) to delete the element from the
for elif ch==2:
a=input("Enter any number else: stack created in the previous question and provide
Index")) print("Books in Stack")
("Enter the pop(Emp) the given output. Also write the function calling
ind=int (input
if len(s)<ind : l=len(Book) elif ch==3: statement.
exist, Will add at
print ("Index not for i in range(1-1, -1,-1): display (Emp) LALAN
else:
the last")
S. append(a)
print (Book[i),"<=", end="") KAMAL
break
# main
else:
[Link](ind, a) Book-[) 33. #Write the functions push and display implemented AMAR
elif (choices=2): while True: through stack. ASsuming the given list insert the Stack is Emptied
elements into the stacks which start from A.
if (s=()): DrÍnt("\n1. Push\n2. Pop \n3. Displayn4. Erien Ans. def pop(Players):
print ("List Empty") Ans. l=["Amit", "Abhinav","Deb", "Raj", "Ankit", "Naveen"]
ch=int(input ("Enter your choice")) if Players-- []:
else:
print("1. Deletion from the end\n 2.
if ch==1: st=[) return "Stack is Emptied"
push (Book) def push(st, 1): else:
Deletion of particular Value") for i in l:
n=int (input("Enter your choice")) elifch==2: return Players. pop()
if i[0]=-'A': for i in range(len (Players) ·1) :
if n==1: pop (Book)
print ("Deleted element is: [Link](1) print (pop (Players) )
elifch==3:
",[Link]() def display (st) :
display (Book) 36. Assuming the given dictionary, Write the function to
else: if st--[]:
else: print ("underflow")s6 push add new element in the stack. Add only those
de=input("Enter the element to
be removed") break else:0 element from the dictonary whose value consist of
[Link] (de) for i in range(len(st) -1,-1,-1): 'A, 'E' or 'I.
32. Write a menu driven python program using function Ans. d={"INDIA": "DELHI", "PAKISTAN":"LAHORE"}
elif (choice--3): print (st[i])
l-len(s) Push (), Pop ) and Display) to implement the stack push(st, 1) c=[]
for i in range(0,1): The program will store the Employee details ie def push(c):
display(st)
print(s[i]) Employee number, Employee name and Salary. for i in d:
else: 34. Write a function push) to implement the stack and if "A in d[i] or "E" in d[i] or 'I' in d[il:
Ans. def push(Emp): add the alternate element of list to the stack. Also
print("Wrong Input") [Link](d[i])
C=input ("Do you want to continue or not? ") eno=int (input("Enter the Empolyee Number")) write the function calling statement.
print(c)
30. Write Push(Book) and Pop(Book) methods in ename=input ("Enter the Employee Name") Ans. def
to Add a new Book and Remove a Book Python push(c)
from a List sal=input ("Enter the Salary") push(Players,N):
of Books, considering them to act as PUSH
operations of the data structure Stack.
and POP Emp. append( [eno, ename, sal])
Ans. def push(Book): def pop(Emp): PRACTICE OUESTION BANK
a=input("Enter any number :") if Emp=-[0: 4, Choose the correct output from the given output options
print("Under Flow") I. Write the single statemnent that reverse the list.
[Link](a) for the following code.
def pop(Book): else: bo Write a Python program to select the even items of a a= (1, 2, 3, 4, 5]
if (Book==)): list
Print ("Enployee Record Deleted",[Link])) for i in range(1, 5):
print ("Stack Empty") def display(Emp): 3. What is the output of the following code?
else: a[i-1] a[i)
print ("Deleted element if Emp==[): def unpack(a, b, c, d): for i in range(0, 5):
31. Write a menu
driven python is:",[Link]()) print("Underflow!!!") print(a+d) print (a[i],end = " ")
Push), Pop) and Display) toprogram using function else: X = [1,2.3.4] i. 5 5 1 2 3
The program will implement the stack. unpack(*x)
Ans. def push(Book): store the name of the books. print("Employee record in Stack\n i. Error
ii. 5 1 2 3 4
1-len(Emp) iii. 2 3 4 5 1
name=input("Enter the book name" for i in ii, [1,4].
range(1-1, -1,-1): iii. [5]. iv. 2 3 45 5
print (Enp[i]) iv. 5
(Pthon)-12
agetker uctk Computer Science
9. Assertion (A): The time complexity
of push
120 using an P
code?
of the following onerations on a stack implemented
5. What is the output
def change (var, lst): O(1).
var = 1 Reason (R): The push and pop operations on an array take
lst[0] = 44 execute, hence O(1) time

k =3
constant time to

(A): The stack data structure is


complexity.
a = (1, 2, 3] 10. Assertion usetul in
converting infix expressions to postfix expressions,
change (k, a)
print (k)
print(a)
Reason (R): In the conversion process, operators with
higher precedence are added to the stack before operators
i. 3
[44, 2, 3]. with lower precedence.
ii. 1

[1,2,3]
iii. 3 Long Answer
[1,2,3].
Type Questionsatg 5 Marks
iv. 1
[44,2,3]. PUSH(insert) operation in stak
given program: 11. Write algorithm for
6. Write the output for the operation in stack
a=[10,20,30,40, 50) 12. Write algorithm for POP(Remove)
as parameter and
for i in range (0, 5) : 13. WAP using Function to take an list
a[i]"-5 elemennt.
print Second largest
print(a) will store the student information
statements: 14. Write a program which
7. Write the output for the given list as follows.
a-[10,20, 30, 40, 50] in the form of a nested
number, avg marks )
i. print (a[0) *for first item (ie: student name, roll
item
ii. print (a[-1]) #FoI Last Example:
iii. print (a[1:]) #FoI Printing the list having 77.5),("Sonali", 103,
2 i.e. student=[ ["Rahul", 100,
all the items from position no. ["Pravit", 102,
a1] onwards 35.5], ["Hrisikesh", 101, 88.0],
having 87.5], ["Tanmaya", 103, 45.5] ]
iv. print (a:1]) #For printing the list initialized the list and
number 1 i.e Your program will
all the items upto position details, those are poor
upto a[o] display the students
From performer (Secured less
than 50% as average
V. print (al:3]) #For printing the List
a[o] to a[2] mark
print (a[1:4]) #For printing the list write a function to
vi. 15. Given a list of numbers (integers),second minimum in
starting from a[1] to a[3] return the second maximum
and
list
vii. print (a[4:1: -1]) #For printing the this list.
fIOm a[4] to a[2]
in reverse starting contains numbers separaleu
viii.
print(a[:0:-1]) #For printing the list in Input: The first line
reverse order upto a[1] by a space.
miniu"
ix. print(a[::-1]) #For printing the entire Output: Print second
maximum and second
list in reverse order
separated by a space
8. Assertion (A): A stack implemented using a linked list Example:
has a fixed size.
Input: 2,7,5,9,1,6
Reason (R): Linked lists are not resizable, hence the
Output: 2 7
stack imnplemented using linked list has a fixed size.

Answers to all unsolved questions are given at the


end of all the chapters

You might also like