Ds Data Structure Lab Manual
Ds Data Structure Lab Manual
(Autonomous)
Dundigal, Hyderabad - 500 043
Lab Manual:
Prepared by
Mr. Y.Mallikarjun (IARE10990)
Page 2
1 Course Information
1.1 Introduction
The laboratory course covers the design and analysis of fundamental data structures and engages
learners to use data structures as tools to algorithmically design efficient computer programs that will
cope with the complexity of actual applications. Data structures knowledge is required of people who
design and develop software e.g. operating systems, language compilers, communications processors
and association list etc.
The student is expected to be prepared for each lab.Lab preparation includes reading the labexperi-
ment and related textbook material. If you have questions or problems with the preparation, contact
your Laboratory Teaching faculty, but in a timely manner. Do not wait until an hour or two befor
the lab and then expect the lab faculty to be immediately available.
Active participation by each student in lab activities is expected. The student is expected to askthe
laboratory faculty any questions they may have.
A large portion of the student’s grade is determined in the comprehensive final exam, resulting in a
requirement of understanding the concepts and procedure of each lab experiment for the successful-
completion of the lab class. The student should remain alert and use common sense while performing
a lab experiment. They are also responsible for keeping a professional and accurate record of the
labexperiments in the lab manual wherever tables are provided. Students should report any errors in
the lab manual to the teaching assistant.
The laboratory faculty shall be completely familiar with each lab prior to class. The laboratory fac-
ulty shall provide the students with a syllabus and safety review during the first class. The syllabus
shall include the laboratory faculty office hours, telephone number, and the name of the faculty coor-
dinator. The laboratory faculty is responsible for ensuring that all the necessary equipment and/or
preparations for the lab are available and in working condition. Lab experiments should be checked
in advance to make sure everything is in working order. The laboratory faculty should fully answer
any questions posed by the students and supervise the students performing the lab experiments. The
laboratory faculty is expected to grade the lab notebooks and reports in a fair and timely manner.
The reports should be returned to the students in the next lab period following submission. The
laboratory faculty should report any errors in the lab manual to the faculty coordinator.
1.6 Attandance:
Attendanceismandatoryandanyabsencemustbeforavalidexcuseandmustbe documented.If the instructor
is more than 15 minutes late, students may consider lab for the daycancelled.
Page 3
1.7 LAB Records:
The student must:
• 1. PerformthePreLabassignmentbeforethebeginningofeachlab,
• 2. Keepallworkinpreparationofandobtainedduringlab;and
• 3. Preparealabreportonexperimentsselectedbythelaboratory faculty.
The final grade of this course is determined using the criterion detailed in thesyllabus.
• Before entering the lab the student should carry the following things (MANDATORY)
• Student must sign in and sign out in the register provided when attending the lab session without
fail.
• Come to the laboratory in time. Students, who are late more than 15 min., will not be allowed
to attend the lab.
• Students need to maintain 100% attendance in lab if not a strict action will be taken.
• Refer to the lab staff if you need any help in using the lab.
• Read the Manual carefully before coming to the laboratory and be sure about what you are
supposed to do.
• Copy all the programs to observation which are taught in class before attending the lab session.
• Students are not supposed to use floppy disks, pen drives without permission of lab- incharge.
• Computer labs are established with sophisticated and high end branded systems, which should
be utilized properly.
• Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab
sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., will attract
severe punishment.
Page 4
• Students must take the permission of the faculty in case of any urgency to go out; if anybody
found loitering outside the lab / class without permission during working hours will be treated
seriously and punished appropriately.
• Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the lab
after completing the task (experiment) in all aspects. He/she must ensure the system / seat is
kept properly.
2.1 Goal:
• The laboratory course covers the design and analysis of fundamental data structures and engages
learners to use data structures as tools to algorithmically design efficient computer programs that
will cope with the complexity of actual applications. Data structures knowledge is required of
people who design and develop software e.g. operating systems, language compilers, communi-
cations processors and association list etc. It is designed to develop skills to design and analyze
simple linear and non linear data structures. It strengthen the ability to the students to identify
and apply the suitable data structure for the given real world problem. It enables them to gain
knowledge in practical applications of data structures. Learn different data structures that can
be used to store data. Implement different methods used to manipulate these data structures
and examine the efficiency. Understand the advantages and applications of different data struc-
tures. Learn how to approach open ended problems (either in interview or real-world) and select
appropriate data structures based on requirements.
2.2 Objectives:
• The skills needed to understand and analyze performance trade-offs of different algorithm im-
plementations and asymptotic analysis of their running time and memory usage.
• Develop the abilities of critical analysis to reduce the time and space complexity of algorithms
for particular given problem
• Provide knowledge of basic abstract data types (ADT) and associated algorithms: stacks, queues,
lists, tree, graphs, hashing and sorting, selection and searching.
• Provide the fundamentals of Non-linear Data structure to store, retrieve, and process data
efficiently.
• Apply graph and trees algorithms to solve real-world challenges such as finding shortest paths
on huge maps and assembling genomes from millions of pieces.
Students must write their experimental outputs in the provided tables in this laboratory manual and
reproduce them in the lab reports. Reports are integral to recording the methodology and results
of an experiment. In engineering practice, the laboratory notebook serves as an invaluable reference
to the technique used in the lab and is essential when trying to duplicate a result or write a report.
Therefore, it is important to learn to keep accurate data. Make plots of data and sketches when these
are appropriate in the recording and analysis of observations. Note that the data collected will be an
Page 5
accurate and permanent record of the data obtained during the experiment and the analysis of the
results. You will need this record when you are ready to prepare a lab report.
Reports are the primary means of communicating your experience and conclusions to other profes-
sionals. In this course you will use the lab report to inform your laboratory facultyabout what you
did and what youhave learned from the experience.Engineering results are meaningless unless they
can be communicatedto others. You will be directed by your laboratory facultyto prepare a lab report
on a few selected lab experimentsduringthesemester.Your assignment might be different from your
labpartner’sassignment. Your laboratory report should be clear and concise.The lab report shall be
typed on a word processor.As a guide,use the format on the next page.Use tables,diagrams, sketches,
as necessaryto show what you did, what was observed, and what conclusions you can draw from this.
Even thoughyou will work with one or more lab partners, your report will be the result of your indi-
vidual effort inordertoprovideyouwith practice in technical communication.
• Bodytextshouldbedouble-spaced.
• Basictextshouldbein12-pointsizeinacommonlyusedtextfont.
• Setyourmaintextjustified(withevenleft/rightmargins).
• Thefirstlineofeachparagraphshouldhavealeftindent.
• All the tables should have titles and should be numbered. Tables should be labeled numericallyas
Table 1, Table 2, etc. Table captions appear above the table. The column headings should
belabeledwiththeunitsspecified.
• Use MS-Word equation (under InsertEquation menu), MathType, or a similar tool to typefor-
mulas.
• If you need to copy as chematicor figure from the lab manual to your report,use Copy and Paste
function or take a screen shot by using Snipping Tool in MS-Windows.
• Do not place screenshots of your lab notebook in the report! Diagrams, tables, calculations,
etc.must be generate dusing the existing tools in the word processor.
3.5.1 Coverpage:
, Cover page must include lab nameand number,your name,your lab partner’s name,and the date the
lab was performed.
3.5.2 Objective:
, Clearly state the experiment objective in your own words.
Page 6
• Writethelab’spartnumberandtitleinboldfont. Firstly, describe the problem that you studied in
this part, give an introduction of the theory, andexplain why you did this experiment.Do not lift
the text from the lab manual; use your ownwords.
• Secondly,describe the experimental setup and procedures. Do not follow the lab manual in listing
out individual pieces of equipment and assembly instructions.That is not relevant in formation
in alabreport! Your description should take the form of a narrative, and include information
notpresent in the manual,such as descriptions of what happened during intermediate steps of
theexperiment.
• Finally, provide a summary of what was learned from this part of the laboratory experiment. If
the results seemun expected or unreliable,discuss the man give possible explanations.
4 Conclustions:
The conclusion section should provide a take-home message summing up what has been learned from
the experiment:
• Brieflyrestatethepurposeoftheexperiment(thequestionitwasseekingtoanswer)
• Identifythemainfindings(answertotheresearchquestion)
• Notethemainlimitationsthatarerelevanttotheinterpretationoftheresults
• Summarizewhattheexperimenthascontributedtoyourunderstandingoftheproblem.
Questionspertainingtothislabmustbeansweredattheendoflaboratoryreport.
Page 7
Week -1 Searching Techniques
Introduction
Searching in data structure refers to the process of finding location LOC of an element in a list. This is
one of the important parts of many data structures algorithms, as one operation can be performed on
an element if and only if we find it. Various algorithms have been defined to find whether an element is
present in the collection of items or not. This algorithm can be executed on both internal as well as ex-
ternal data structures. The efficiency of searching an element increases the efficiency of any algorithm.
Objective
Python 3.7.3
python jupyter notebook
Background
Searching Algorithms are designed to check for an element or retrieve an element from any data struc-
ture where it is stored. Based on the type of search operation, these algorithms are generally classified
into two categories:
1. Linear Search.
In this, the list or array is traversed sequentially and every element is checked A simple approach is
to do a linear search, i.e.
• Start from the leftmost element of arr[] and one by one compare x with each element of arr[]
• Linear search is rarely used practically because other search algorithms such as the binary
search algorithm and hash tables allow significantly faster-searching comparison to Linear search.
These algorithms are specifically designed for searching in sorted data-structures. These type of search-
ing algorithms are much more efficient than Linear Search as they repeatedly target the center of the
search structure and divide the search space in half. Search a sorted array by repeatedly dividing the
search interval in half. Begin with an interval covering the whole array. If the value of the search key
is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise,
narrow it to the upper half. Repeatedly check until the value is found or the interval is empty. Binary
Page 8
Search to find the element “23” in a given list of numbers
Procedure
a. Create:
Open a new file in Python shell, write a program and save the program with .py extension.
b. Execute:
Go to Run -> Run module (F5)
Program logic:
Given a list of n elements and search a given element x in the list using linear search.
a. Start from the leftmost element of list a[] and one by one compare x with each element
of list a[].
b. If x matches with an element, return the index.
a. If x doesn’t match with any of elements, return -1.
Source Code
d e f l i n e a r _ s e a r c h ( obj , item ) :
f o r i in range ( len ( obj ) ) :
i f o b j [ i ] == item :
r e t u r n i r e t u r n −1
#D r i v e r code a r r = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]
x=i n t ( i n p u t ( ” what a r e you s e a r c h i n g f o r ? ” ) )
r e s u l t=l i n e a r _ s e a r c h ( a r r , x )
i f r e s u l t ==−1:
p r i n t ( ” e l e m e n t d o e s not e x i s t ” )
else :
p r i n t ( ” e l e m e n t e x i s t i n p o s i t i o n %d” %r e s u l t ) \ \
Ouptut:
Page 9
Binary search technique:
• A newspaper route has recently been computerized. Information about each of the 100 customers
is stored in individual records containing first name, last name, and payment due. In writing
a computer program to process the customer records, the programmer is uncertain whether to
add a procedure to sort the records. If the records are first sorted, what will be the maximum
number of comparisons needed with a binary search to find a particular customer’s record?
• A person has registered for voter id, he received a voter number and he need to check whether
Page 10
it exist in the voter or not. Use a binary searching in a recursive way to find whether the voter
number exist in the list or not
• Use linear search technique to search for a key value in a given list of characters and print the
message found or not.
VIVA QUESTIONS
Page 11
Week -2 Sorting Techniques
Introduction
Sorting is nothing but arranging the data in ascending or descending order. The term sorting came
into picture, as humans realized the importance of searching quickly. There are so many things in our
real life that we need to search for, like a particular record in database, roll numbers in merit list, a
particular telephone number in telephone directory, a particular page in a book etc. All this would
have been a mess if the data was kept unordered and unsorted, but fortunately the concept of sorting
came into existence, making it easier for everyone to arrange data in an order, hence making it easier
to search.
Objectives
• Learn to arrangement of data in the memory in the best possible way such that if somebody
needs some data, one can find it easily in the quickest time.
• Learn to rearrange the data in memory so that the Memory consumed by the data is minimum.
• To be able to explain and implement selection sort, bubble sort, merge sort, quick sort, insertion
sort, and shell sort
Experimental
• Implement the sorting techniques to rearrange the records so that their keys are ordered
according to some well-defined ordering rule.
PreLab
Reading
Written
• Prior to coming to lab class, complete worksheet with complete sorting logic.
Software Needed
• Python 3.7.3
Page 12
Background
A Sorting Algorithm is used to rearrange a given array or list elements according to a comparison
operator on the elements. The comparison operator is used to decide the new order of element in the
respective data structure. sorting techniques and their algorithms used to manipulate data structure
and its storage. Sorting method can be implemented in different ways - by selection, insertion method,
or by merging. The techniques of sorting can be divided into two categories. These are:
Internal Sorting:
External Sorting:
Internal Sorting:
If all the data that is to be sorted can be adjusted at a time in the main memory, the internal sorting
method is being performed.
External Sorting:
When the data that is to be sorted cannot be accommodated in the memory at the same time and
some has to be kept in auxiliary memory such as hard disk, floppy disk, magnetic tapes etc, then
external sorting methods are performed. The complexity of sorting algorithms The complexity of
sorting algorithm calculates the running time of a function in which ’n’ number of items are to be
sorted. The choice for which sorting method is suitable for a problem depends on several dependency
configurations for different problems. The most noteworthy of these considerations are: The length of
time spent by the programmer in programming a specific sorting program Amount of machine time
necessary for running the program The amount of memory necessary for running the program
To get the amount of time required to sort an array of ’n’ elements by a particular method, the normal
approach is to analyze the method to find the number of comparisons (or exchanges) required by it.
Most of the sorting techniques are data sensitive, and so the metrics for them depends on the order
in which they appear in an input array. Various sorting techniques are analyzed in various cases and
named these cases as follows: Best case Best case Worst case Average case
Types of sorting techniques
• Bubble Sort
• Selection Sort
• Merge Sort
• Insertion Sort
• Quick Sort
• Heap Sort
Procedure
• a. Create:
Open a new file in Python shell, write a program and save the program with .py extension.
• b. Execute:
Go to Run -> Run module (F5)
Page 13
Program logic:
\ t e x t b f { Bubble s o r t : } \ \
bubbleSort ( arr )
• a. Suppose we have a O(n) time algorithm that finds median of an unsorted array. Now consider
a QuickSort implementation where we first find median using the above algorithm, then use
median as pivot. What will be the worst case time complexity of this modified QuickSort
• b. Given an unsorted array. The array has this property that every element in array is at most k
distance from its position in sorted array where k is a positive integer smaller than size of array.
Page 14
Which sorting algorithm can be easily modified for sorting this array and what is the obtainable
time complexity?
• c. Consider a situation where swap operation is very costly. Which of the following sorting
algorithms should be preferred so that the number of swap operations are minimized in general?
VIVA QUESTIONS
Page 15
Week -3 Sorting Techniques
Introduction
Sorting is nothing but arranging the data in ascending or descending order. The term sorting came
into picture, as humans realized the importance of searching quickly.
There are so many things in our real life that we need to search for, like a particular record in database,
roll numbers in merit list, a particular telephone number in telephone directory, a particular page in
a book etc.
All this would have been a mess if the data was kept unordered and unsorted, but fortunately the
concept of sorting came into existence, making it easier for everyone to arrange data in an order, hence
making it easier to search.
Objectives
Educational
Learn to arrangement of data in the memory in the best possible way such that if somebody needs
some data, one can find it easily in the quickest time.
Learn to rearrange the data in memory so that the Memory consumed by the data is minimum.
Learn to Memory fragmentation is minimum when data is manipulated(add/remove/update).
To be able to explain and implement selection sort, bubble sort, merge sort, quick sort, insertion sort,
and shell sort
Experimental
Implement the sorting techniques to rearrange the records so that their keys are ordered accord-
ing to some well-defined ordering rule.
PreLab
Reading
Read and study the Background section of this Laboratory. Explain the term sorting? What are the
different types of sorts in data structures? Define the quick sort? Define the merge sort?
Written
Prior to coming to lab class, complete worksheet with complete sorting logic.
Software Needed
Python 3.7.3
Python Jupyter Notebook
python jupyter notebook
Background
Quick sort is a fast sorting algorithm used to sort a list of elements. Quick sort algorithm is invented
by C. A. R. Hoare. The quick sort algorithm attempts to separate the list of elements into two parts
Page 16
and then sort each part recursively. That means it use divide and conquer strategy. In quick sort,
the partition of the list is performed based on the element called pivot. Here pivot element is one of
the elements in the list. The list is divided into two partitions such that ”all elements to the left of
pivot are smaller than the pivot and all elements to the right of pivot are greater than or equal to the
pivot”.
In Quick sort algorithm, partitioning of the list is performed using following steps...
• Step 1 - Consider the first element of the list as pivot (i.e., Element at first position in the list).
• Step 2 - Define two variables i and j. Set i and j to first and last elements of the list respectively.
Procedure
a. Create:
Open a new file in Python shell, write a program and save the program with .py extension.
b. Execute:
Program logic:
\ textbf { quicksort }
# Python program f o r i m p l e m e n t a t i o n o f Q u i c k s o r t S o r t
# This f u n c t i o n t a k e s l a s t e l e m e n t a s p i v o t , p l a c e s
# the pivot element at i t s c o r r e c t p o s i t i o n in s o r t e d
# array , and p l a c e s a l l s m a l l e r ( s m a l l e r than p i v o t )
# t o l e f t o f p i v o t and a l l g r e a t e r e l e m e n t s t o r i g h t
# of pivot
d e f p a r t i t i o n ( a r r , low , h i g h ) :
i = ( low −1) # index of s m a l l e r element
pivot = arr [ high ] # pivot
f o r j i n r a n g e ( low , h i g h ) :
# I f c u r r e n t e l e m e n t i s s m a l l e r than o r
# equal to pivot
i f a r r [ j ] <= p i v o t :
# increment index o f s m a l l e r element
i = i +1
arr [ i ] , arr [ j ] = arr [ j ] , arr [ i ]
a r r [ i +1] , a r r [ h i g h ] = a r r [ h i g h ] , a r r [ i +1]
r e t u r n ( i +1)
# The main f u n c t i o n t h a t implements QuickSort
Page 17
# a r r [ ] −−> Array t o be s o r t e d ,
# low −−> S t a r t i n g index ,
# h i g h −−> Ending i n d e x
# Function t o do Quick s o r t
arr = [10 , 7 , 8 , 9 , 1 , 5]
n = len ( arr )
q u i c k S o r t ( a r r , 0 , n−1)
print (” Sorted array i s : ” )
f o r i in range (n ) :
p r i n t (”%d” % a r r [ i ] ) ,
# D r i v e r code t o t e s t above
d e f q u i c k S o r t ( a r r , low , h i g h ) :
i f l e n ( a r r ) == 1 :
return arr
i f low < h i g h :
# p i i s p a r t i t i o n i n g index , a r r [ p ] i s now
# at r i g h t place
p i = p a r t i t i o n ( a r r , low , h i g h )
# Separately sort elements before
# p a r t i t i o n and a f t e r p a r t i t i o n
q u i c k S o r t ( a r r , low , pi −1)
q u i c k S o r t ( a r r , p i +1, h i g h )
OUTPUT
bubble sort
insertion sort
selection sort
Page 18
PROBING FURTHER QUESTIONS
• Lauren has a chart of distinct projected prices for a house over the next several years. She must
buy the house in one year and sell it in another, and she must do so at a loss. She wants to
minimize her financial loss. Example prince=20,15,8,2,12
Her minimum loss is incurred by purchasing in year 2 at price[1]=15 and reselling in year 5 at
price[4]=12 . Return 15-12=3 .
VIVA QUESTIONS
Page 19
Week -4 Implementation of Stack and Queue
Introduction
Stacks, queues, deques, and lists are data collections with items ordered according to how they are
added or removed. Once an item is added, it stays in the same position relative to its neighbors.
Because of this characteristic, we call these collections linear data structures. Both stacks and queues
are like lists (ordered collections of items), but with more restricted operations. They can both be
implemented either using an array or using a linked list to hold the actual items.
Objectives
Educational
To understand the abstract data types stack, queue, deque, and list. To be able to implement the
ADTs stack, queue, and deque using Python lists To be able to recognize problem properties where
stacks, queues, and deques are appropriate data structures. To understand prefix, infix, and postfix
expression formats. To use stacks to evaluate postfix expressions.
Experimental
PreLab
Reading
• What is stack?
• What is recursion?
• Define a queue?
• Define a queue.
Page 20
• List out the applications of queue?
Written
Prior coming to the this lab, students has to complete the worksheet with stack and queue program
in python
Software Needed
Python 3.7.3
Python Jupyter Notebook
Background
Stacks:
A stack is an ordered collection of items where the addition of new items and the removal of existing
items always takes place at the same end. This end is commonly referred to as the “top”, and the
opposite end is known as the “base”. There are many examples of stacks in everyday situations. Con-
sider a stack of plates on a table, where it’s only possible to add or remove plates to or from the top.
Or imagine a stack of books on a desk. The only book whose cover is visible is the one on top. To
access the others, we must first remove the ones sitting on top of them. The interface for a stack is:
Stack() creates a new, empty stack push(item) adds the given item to the top of the stack and returns
nothing pop() removes and returns the top item from the stack peek() returns the top item from
the stack but doesn’t remove it (the stack isn’t modified) is-empty() returns a boolean representing
whether the stack is empty size() returns the number of items on the stack as an integer
Queue:
A queue is an ordered collection of items where the addition of new items happens at one end, called
the “rear,” and the removal of existing items occurs at the other end, commonly called the “front.”
As an element enters the queue it starts at the rear and makes its way toward the front, waiting until
that time when it is the next element to be removed. The most recently added item in the queue
must wait at the end of the collection. The item that has been in the collection the longest is at
the front. This ordering principle is sometimes called FIFO, first-in first-out. It is also known as
“first-come first-served.” The simplest example of a queue is the typical line that we all participate
in from time to time. We wait in a line for a movie, we wait in the check-out line at a grocery store,
and we wait in the cafeteria line (so that we can pop the tray stack). Well-behaved lines, or queues,
are very restrictive in that they have only one way in and only one way out. There is no jumping in
the middle and no leaving before you have waited the necessary amount of time to get to the front.
The queue operations are: Queue() creates a new queue that is empty. It needs no parameters and
returns an empty queue. enqueue(item) adds a new item to the rear of the queue. It needs the item
and returns nothing. dequeue() removes the front item from the queue. It needs no parameters and
returns the item. The queue is modified. is-empty() tests to see whether the queue is empty. It needs
no parameters and returns a boolean value. size() returns the number of items in the queue. It needs
no parameters and returns an integer.
Procedure
a. Create:
Open a new file in Python shell, write a program and save the program with .py extension.
b. Execute:
Page 21
Go to Run -> Run module (F5)
Stack is a linear data structure which works under the principle of last in first out. Basic operations:
• push
• pop
• display.
PUSH:
if (top==MAX), display Stack overflow. Otherwise reading the data and making stack [top]=data
and incrementing the top value by doing top++.
Pop:
if (top==0), display Stack underflow. Otherwise printing the element at the top of the stack and
decrementing the top value by doing the top.
DISPLAY:
If (top==0), display Stack is empty. Otherwise printing the elements in the stack from stack[0] to
stack [top].
Queue and its operations using list:
Queue is a linear data structure which works under the principle of first in first out. Basic operations:
Insertion, deletion, display.
Inserion:
if (rear==MAX), display Queue is full. Else reading data and inserting at queue [rear], and doing
rear++.
Deletion:
if (front==rear), display Queue is empty .Else printing element at queue [front] and doing front++.
Display:
if (front==rear) ,display No elements in the queue .Else printing the elements from queue[front] to
queue[rear].
Program logic:
\ t e x t b f { Stack and i t s o p e r a t i o n s u s i n g l i s t : } \ \
# Function t o c r e a t e a s t a c k . I t i n i t i a l i z e s s i z e o f s t a c k a s 0 d e f c r e a t e S t a c k ( ) :
stack = [ ]
return stack
# Stack i s empty when s t a c k s i z e i s 0 d e f isEmpty ( s t a c k ) :
r e t u r n l e n ( s t a c k ) == 0
# Function t o add an item t o s t a c k . I t i n c r e a s e s s i z e by 1 d e f push ( s t a c k , item ) :
i f ( l e n ( s t a c k)== s i z e ) :
print (” overflow ”)
return
s t a c k . append ( item )
# Function t o remove an item from s t a c k . I t d e c r e a s e s s i z e by 1 d e f pop ( s t a c k ) :
i f ( isEmpty ( s t a c k ) ) : p r i n t ( ” u n d e r f l o w ” )
return
r e t u r n s t a c k . pop ( )
#Function t o know peek e l e m e n t d e f peek ( s t a c k ) :
i f ( isEmpty ( s t a c k ) ) : p r i n t ( ” s t a c k empty ” ) r e t u r n
Page 22
else :
n=l e n ( s t a c k )
p r i n t ( ” peek e l e m e n t i s : ” , s t a c k [ n −1])
#Function t o d i s p l a y s t a c k d e f d i s p l a y ( s t a c k ) :
print ( stack )
# D r i v e r program t o t e s t above f u n c t i o n s s t a c k = c r e a t e S t a c k ( ) s i z e=i n t ( i n p u t ( ” e n t e
p r i n t ( ”Menu\n1 . push ( p ) \ n2 . pop ( o ) \ n3 . peek ( e ) ” ) c h o i c e =1
w h i l e c h o i c e != ' q ' : p r i n t ( ” e n t e r your c h o i c e ” ) ch=i n p u t ( ) c h o i c e=ch . l o w e r ( )
i f c h o i c e =='p ' :
push ( s t a c k , i n t ( i n p u t ( ” e n t e r a v a l u e ” ) ) )
display ( stack )
e l i f c h o i c e =='o ' : pop ( s t a c k ) d i s p l a y ( s t a c k )
e l i f c h o i c e =='e ' : peek ( s t a c k )
else :
p r i n t (” enter proper ch oi ce or q − quit ”)
global f
i f r==−1 and f ==−1: r=0
f =0 a . i n s e r t ( r , item )
e l i f r==(n −1): p r i n t ( ” o v e r f l o w ” ) r e t u r n
else :
r+=1
a . i n s e r t ( r , item ) d i s p l a y ( a )
d e f dequeue ( a ) : g l o b a l r g l o b a l f
i f r==(n−1) and f ==(n −1): item=a [ f ]
r=−1 f=−1
e l i f r==−1 and f ==−1: p r i n t ( ” u n d e r f l o w ” ) r e t u r n
else :
item=a [ f ] f+=1
p r i n t ( ” d e l e t e d item i s : ” , item ) d i s p l a y ( a )
def display (a ) :
p r i n t ( ” \ n c u r r e n t queue i s : ” ) f o r i i n r a n g e ( f , r +1):
i f f==−1 and r==−1: p r i n t ( ” Queue i s empty ! ” ) r e t u r n
p r i n t ( a [ i ] , end=” ” )
#DC
n=i n t ( i n p u t ( ” e n t e r t h e s i z e o f l i s t ” ) ) a = [ ]
r=−1 f=−1
p r i n t ( ”Menu\n1 . enqueue ( e ) \ n2 . dequeue ( d ) \ n3 . e x i t ( q ) ” )
c h o i c e =1
w h i l e c h o i c e != ' q ' : p r i n t ( ” e n t e r your c h o i c e ” ) ch=i n p u t ( ) c h o i c e=ch . l o w e r ( )
i f c h o i c e =='e ' :
enqueue ( a , i n t ( i n p u t ( ” e n t e r a v a l u e ” ) ) ) d i s p l a y ( a )
e l i f c h o i c e =='d ' : dequeue ( a ) d i s p l a y ( a )
else :
print (” enter proper choice ”)
OUTPUT
Page 23
Stack and its operations using list:
• There is a garage where the access road can accommodate any number of trucks at one time.
The garage is building such a way that only the last truck entered can be moved out. Each
of the trucks is identified by a positive integer (a truck-id). Write a program to handle truck
moves, allowing for the following commands:
– On-road (truck-id)
– Ente-garage (truck- id)
– Exit-garage (truck-id);
– Show-trucks (garage or road)
If an attempt is made to get out a truck which is not the closest to the garage entry, the error
message Truck x not near garage door.
Page 24
• Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(),
isEmpty(), isFull() and an additional operation getMin() which should return minimum element
from the SpecialStack. All these operations of SpecialStack must be O(1). To implement Spe-
cialStack, you should only use standard Stack data structure and no other data structure like
arrays, list, . etc.
• A queue is an abstract data type that maintains the order in which elements were added to it,
allowing the oldest elements to be removed from the front and new elements to be added to
the rear. This is called a First-In-First-Out (FIFO) data structure because the first element
added to the queue (i.e., the one that has been waiting the longest) is always the first one to be
removed.
VIVA QUESTIONS
Page 25
Week -5 Applications of Stack
Introduction
Stacks can be used for expression evaluation. Stacks can be used to check parenthesis matching in an
expression. Stacks can be used for Conversion from one form of expression to another. Stacks can be
used for Memory Management. Stack data structures are used in backtracking problems
Objectives
Educational
Learn to arrangement of data in the memory in the best possible way such that if somebody needs
some data, one can find it easily in the quickest time.
Learn to rearrange the data in memory so that the Memory consumed by the data is minimum.
Learn to Memory fragmentation is minimum when data is manipulated(add/remove/update).
To be able to explain and implement selection sort, bubble sort, merge sort, quick sort, insertion sort,
and shell sort
Experimental
Write a Python script that uses stack operations to convert infix expression to postfix expression.
Write a Python script that uses stack operations for evaluating the postfix expression.
PreLab
Reading
• What is an expression?
Written
Prior to coming to lab class, complete worksheet with complete sorting logic.
Software Needed
• Python 3.7.3
Background
Following are some of the important applications of a Stack data structure: Stacks can be used for
expression evaluation. Stacks can be used to check parenthesis matching in an expression. Stacks
Page 26
can be used for Conversion from one form of expression to another. Stacks can be used for Memory
Management. Stack data structures are used in backtracking problems.
Expression Evaluation:
Stack data structure is used for evaluating the given expression. For example, consider the following
expression 5 * ( 6 + 2 ) - 12 / 4 Since parenthesis has the highest precedence among the arithmetic
operators, ( 6 +2 ) = 8 will be evaluated first. Now, the expression becomes 5 * 8 - 12 / 4 * and / have
equal precedence and their associativity is from left-to-right. So, start evaluating the expression from
left-to-right. 5 * 8 = 40 and 12 / 4 = 3 Now, the expression becomes 40 - 3 And the value returned
after the subtraction operation is 37. Parenthesis Matching Given an expression, you have to find if
the parenthesis is either correctly matched or not. For example, consider the expression ( a + b ) * (
c + d ). In the above expression, the opening and closing of the parenthesis are given properly and
hence it is said to be a correctly matched parenthesis expression. Whereas, the expression, (a + b *
[c + d ) is not a valid expression as the parenthesis are incorrectly given.
Expression Conversion:
Converting one form of expressions to another is one of the important applications of stacks.
• Infix to prefix
• Infix to postfix
• Prefix to Infix
• Prefix to Postfix
• Postfix to Infix
• Postfix to Infix
Memory management:
The assignment of memory takes place in contiguous memory blocks. We call this stack memory
allocation because the assignment takes place in the function call stack. The size of the memory to
be allocated is known to the compiler. When a function is called, its variables get memory allocated
on the stack. When the function call is completed, the memory for the variables is released. All this
happens with the help of some predefined routines in the compiler. The user does not have to worry
about memory allocation and release of stack variables.
Procedure
a. Create:
Open a new file in Python shell, write a program and save the program with .py extension.
b. Execute:
Program logic:
Page 27
Let, X is an arithmetic expression written in infix notation. This algorithm finds the equivalent postfix
expression Y.
• 2. Scan X from left to right and repeat Step 3 to 6 for each element of X until the Stack is
empty.
• – 1. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) which has
the same precedence as or higher precedence than operator.
– 2. Add operator to Stack. [End of If]
– 1. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) until a left
parenthesis is encountered.
– 2. Remove the left Parenthesis. [End of If]
[End of If]
• 7. END.
• 2. Scan the given expression and do following for every scanned element.
• 2. If the element is a operator, pop operands for the operator from stack. Evaluate the operator
and push the result back to the stack
• 3. When the expression is ended, the number in the stack is the final answer
Source Code:
I n f i x e x p r e s s i o n to p o s t f i x e x p r e s s i o n :
import s t r i n g c l a s s C o n v e r s i o n :
# Constructor to i n i t i a l i z e the c l a s s v a r i a b l e s def i n i t ( s e l f , capacity ) :
s e l f . top = −1 s e l f . c a p a c i t y = c a p a c i t y
# This a r r a y i s used a s t a c k s e l f . a r r a y = [ ]
# P r e c e d e n c e s e t t i n g s e l f . output = [ ]
s e l f . precedence = { '+ ':1 , ' − ':1 , ' ∗ ' : 2 , ' / ' : 2 , '^ ':3}
# check i f t h e s t a c k i s empty d e f isEmpty ( s e l f ) :
r e t u r n True i f s e l f . top == −1 e l s e F a l s e
# Return t h e v a l u e o f t h e top o f t h e s t a c k d e f peek ( s e l f ) :
r e t u r n s e l f . a r r a y [ −1]
# Pop t h e e l e m e n t from t h e s t a c k d e f pop ( s e l f ) :
i f not s e l f . isEmpty ( ) : s e l f . top −= 1
r e t u r n s e l f . a r r a y . pop ( ) e l s e :
return ”$”
Page 28
# Push t h e e l e m e n t t o t h e s t a c k d e f push ( s e l f , op ) :
s e l f . top += 1 s e l f . a r r a y . append ( op )
# A u t i l i t y f u n c t i o n t o check i s t h e g i v e n c h a r a c t e r # i s operand
d e f isOperand ( s e l f , ch ) :
r e t u r n ch . i s a l p h a ( )
# Check i f t h e p r e c e d e n c e o f o p e r a t o r i s s t r i c t l y # l e s s than top o f s t a c k o r not
def notGreater ( s e l f , i ) : try :
a = s e l f . precedence [ i ]
b = s e l f . p r e c e d e n c e [ s e l f . peek ( ) ] r e t u r n True i f a <= b e l s e F a l s e
e x c e p t KeyError : r e t u r n F a l s e
# The main f u n c t i o n t h a t c o n v e r t s g i v e n i n f i x e x p r e s s i o n # t o p o s t f i x e x p r e s s i o n
d e f i n f i x T o P o s t f i x ( s e l f , exp ) :
# I t e r a t e o v e r t h e e x p r e s s i o n f o r c o n v e r s i o n f o r i i n exp :
# I f t h e c h a r a c t e r i s an operand , # add i t t o output
i f s e l f . isOperand ( i ) : s e l f . output . append ( i )
# I f t h e c h a r a c t e r i s an ' ( ' , push i t t o s t a c k
e l i f i == ' ( ' :
s e l f . push ( i )
# I f t h e scanned c h a r a c t e r i s an ' ) ' , pop and # output from t h e s t a c k u n t i l and ' (
w h i l e ( ( not s e l f . isEmpty ( ) ) and s e l f . peek ( ) != ' ( ' ) : a = s e l f . pop ( )
s e l f . output . append ( a )
i f ( not s e l f . isEmpty ( ) and s e l f . peek ( ) != ' ( ' ) : r e t u r n −1
else :
s e l f . pop ( )
# An o p e r a t o r i s e n c o u n t e r e d e l s e :
w h i l e ( not s e l f . isEmpty ( ) and s e l f . n o t G r e a t e r ( i ) ) : s e l f . output . append ( s e l f . pop ( ) )
s e l f . push ( i )
# pop a l l t h e o p e r a t o r from t h e s t a c k w h i l e not s e l f . isEmpty ( ) :
s e l f . output . append ( s e l f . pop ( ) )
r e s u l t= ” ” . j o i n ( s e l f . output ) p r i n t ( r e s u l t )
# D r i v e r program t o t e s t above f u n c t i o n exp = ” a+b ∗ ( c ^d−e ) ^ ( f+g∗h)− i ”
o b j = C o n v e r s i o n ( l e n ( exp ) ) o b j . i n f i x T o P o s t f i x
OUTPUT
Page 29
Infix expression to postfix expression:
• Design a Data Structure Special Stack that supports all the stack operations like push(), pop(),
isEmpty(), isFull() and an additional operation getMin() which should return minimum element
from the SpecialStack. All these operations of SpecialStack must be O(1). To implement Spe-
cialStack, you should only use standard Stack data structure and no other data structure like
arrays, list, . etc.
What is the advantage of postfix expression?
• The variable tos in the Stack class is the index of the array element that would be filled the next
time push() is called. Modify the code so that tos is the index of the top element actually in
use. In other words, tos is to be the index of the top array element occupied by a value that has
been “pushed” onto the stack. Write your changes on the code above. Don’t forget to fix the
comments. You do not need to add preconditions as in part-a.
VIVA QUESTIONS
Page 30
Week 6 Implementation of Single Linked List
Introduction
The purpose of this lab session is to acquire skills in working with singly linked lists. A list is a finite
ordered set of elements of a certain type. The elements of the list are called cells or nodes. A list
can be represented statically, using arrays or, more often, dynamically, by allocating and releasing
memory as needed. In the case of static lists, the ordering is given implicitly by the one-dimension
array. In the case of dynamic lists, the order of nodes is set by pointers. In this case, the cells are
allocated dynamically in the heap of the program. Dynamic lists are typically called linked lists, and
they can be singly- or doubly-linked.
Objectives
Educational
Learn to arrangement of data in the memory in the best possible way such that if somebody needs
some data, one can find it easily in the quickest time.
Learn to rearrange the data in memory so that the Memory consumed by the data is minimum.
Learn to Memory fragmentation is minimum when data is manipulated(add/remove/update).
To be able to explain and implement selection sort, bubble sort, merge sort, quick sort, insertion sort,
and shell sort
Experimental
End of the lab students able to compose a program to store and add two polynomial expressions
in memory using linked list. Implement linked list program to delete a given integer from the above
linked list.
Develop a linked list program to display the contents of the above list after deletion
Formulate a program to create a singly linked list and perform insertion, deletion and traversing
operations on a singly linked list
PreLab
Reading
Study the Background section of this Laboratory exercise. Prior coming to the lab students must read
following: What is linked list? What type of memory allocation is used in linked list? How many self
referential pointers are used in single linked list? What is double linked list? Which node contains
NULL pointer in a single linked list? How many nodes you can have in a single linked list? What are
the components of a polynomial expression?
Written
Background
Page 31
Single Linked List: (i) creation (ii) insertion (iii) deletion (iv) traversal (i) Creation:
• Read(Data(first));
• NEXT(First)=NULL;
• X=new node;
• Read(Data(X))
• NEXT(X)=NULL;
• END
(ii) Insertion:
Empty list case: When list is empty, which is indicated by (head == NULL) condition, the insertion
is quite simple. Algorithm sets both head and tail to point to the new node.
In this case, new node is inserted right before the current head node. It can be done in two steps:
• Update the next link of a new node, to point to the current headnode.
In this case, new node is inserted right after the current tail node.
• Update the next link of the current tail node, to point to the newnode
In general case, new node is always inserted between two nodes, which are already in the list. Head
and tail links are not updated in this case. Such an insert can be done in two steps:
Page 32
(vi) Deletion:
List has only one node: When list has only one node, which is indicated by the condition, that the
head points to the same node as the tail, the removal is quite simple. Algorithm disposes the node,
pointed by head (or tail) and sets both head and tail to NULL. Remove first: In this case, first node
(current head node) is removed from the list. It can be done in two steps:
Remove last: In this case, last node (current tail node) is removed from the list. This operation is a
bit trickier, than removing the first node, because algorithm should find a node, which is previous to
the tail first.
It can be done in three steps:
• Update tail link to point to the node, before the tail. In order to find it, list should be traversed
first, beginning from the head.
General case:
In general case, node to be removed is always located between two list nodes. Head and tail links
are not updated in this case. Such a removal can be done in two steps: 1. Update next link of the
previous node, to point to the next node, relative to the removed node. 2. Dispose removed node.
(vii) Traversal:
• count=0;
• count=count+1;
• END
Procedure
a. Create:
Open a new file in Python shell, write a program and save the program with .py extension.
b. Execute:
Program logic:
Page 33
c l a s s Node :
d e f i n i t ( s e l f , data ) : s e l f . data=data s e l f . next=None
class Sll :
d e f i n i t ( s e l f ) : s e l f . s t a r t=None
def c r e a t e l i s t ( s e l f ) :
n=i n t ( i n p u t ( ” e n t e r number o f node ” ) )
f o r i in range (n ) :
data=i n t ( i n p u t ( ” e n t e r v a l u e ” ) ) newnode=Node ( data )
i f s e l f . s t a r t==None : s e l f . s t a r t=newnode
else :
temp= s e l f . s t a r t
w h i l e temp . next !=None : temp=temp . next
temp . next=newnode d e f i n s e r t e n d ( s e l f ) :
n=i n t ( i n p u t ( ” e n t e r v a l u e ” ) ) newnode=Node ( n )
i f s e l f . s t a r t==None : s e l f . s t a r t=newnode
else :
temp= s e l f . s t a r t
w h i l e temp . next !=None : temp=temp . next
temp . next=newnode d e f i n s e r t m i d ( s e l f ) :
n=i n t ( i n p u t ( ” e n t e r v a l u e ” ) ) newnode=Node ( n ) pos=i n t ( i n p u t ( ” e n t e r p o s i t i o n ” ) ) c= s e l f
i f s e l f . s t a r t==None : s e l f . s t a r t=newnode
else :
i f pos >1 and pos<=c : temp= s e l f . s t a r t prev=temp
i =1
w h i l e i <pos : prev=temp temp=temp . next i=i +1
prev . next=newnode newnode . next=temp
d e f d e l e t e m i d ( s e l f ) : count=1
i f s e l f . s t a r t==None : p r i n t ( ” empty ” )
else :
p o s i t i o n=i n t ( i n p u t ( ” e n t e r p o s i t i o n ” ) ) c= s e l f . count ( )
i f p o s i t i o n >c :
p r i n t ( ” check p o s i t i o n ” )
i f p o s i t i o n >1 and p o s i t i o n <c : temp=prev= s e l f . s t a r t w h i l e count<p o s i t i o n :
r e v=temp
temp=temp . next count=count+1
prev . next=temp . next d e l temp
else :
p r i n t ( ” check p o s i t i o n ” )
d e f d e l e t e e n d ( s e l f ) : g l o b a l prev
i f s e l f . s t a r t==None : p r i n t ( ” empty ” )
else :
temp= s e l f . s t a r t prev= s e l f . s t a r t
w h i l e temp . next !=None : prev=temp temp=temp . next
prev . next=None d e l temp
d e f i n s e r t b e g i n ( s e l f ) : n=i n t ( i n p u t ( ” e n t e r v a l u e ” ) ) newnode=Node ( n )
Page 34
i f s e l f . s t a r t==None : s e l f . s t a r t=newnode
else :
temp= s e l f . s t a r t newnode . next=temp s e l f . s t a r t=newnode
def deletebegin ( s e l f ) :
g l o b a l prev
i f s e l f . s t a r t==None : p r i n t ( ” empty ” )
else :
temp= s e l f . s t a r t n e w s t a r t= s e l f . s t a r t . next d e l temp s e l f . s t a r t=n e w s t a r t
def display ( s e l f ) :
print (” elements in s i n g l e linked l i s t are : ” )
i f s e l f . s t a r t==None :
p r i n t ( ” empty ” )
else :
temp= s e l f . s t a r t p r i n t (”%d” %(temp . data ) )
w h i l e temp . next !=None :
temp=temp . next
p r i n t (”%d” %(temp . data ) )
def stop ( ) :
p r i n t ( ” u r about t o t e r m i n a t e program ” ) e x i t ( )
s=S l l ( )
def default ( ) :
p r i n t ( ” check ut i n p u t ” )
menu ( ) w h i l e True :
menu={
1: s . createlist ,
2: s . insertbegin ,
3: s . insertend ,
4: s . insertmid ,
5: s . deletebegin ,
6: s . deleteend ,
7 : s . deletemid ,
8 : s . count ,
9: s . display ,
10: stop }
o p t i o n=i n t ( i n p u t ( ” e n t e r ur c h o i c e ” ) ) menu . g e t ( o p t i o n ) ( )
OUTPUT
• Given a pointer to the head node of a linked list, print each node’s element, one per line. If the
head pointer is null (indicating the list is empty), there is nothing to print.
Given the pointer to the head node of a linked list, change the next pointers of the nodes so
Page 35
Page 36
that their order is reversed. The head pointer given may be null meaning that the initial list is
empty.
• Given a reference to the head of a doubly-linked list and an integer, , create a new Dou-
blyLinkedListNode object having data value and insert it at the proper location to maintain
the sort.
VIVA QUESTIONS
• How many modifications are required to insert a node in the middle of the linked list?
Page 37
Week 7 Implementation of Circular Single Linked List
Introduction
A circular singly linked list is a singly linked list which has the last element linked to the first element
in the list. Being circular it really has no ends; then we’ll use only one pointer node to indicate one
element in the list – the newest element. Figure 2.1 show a model of such a list.
Objectives
Educational
Learn to arrangement of data in the memory in the best possible way such that if somebody needs
some data, one can find it easily in the quickest time.
Learn to rearrange the data in memory so that the Memory consumed by the data is minimum.
Learn to Memory fragmentation is minimum when data is manipulated(add/remove/update).
To be able to explain and implement selection sort, bubble sort, merge sort, quick sort, insertion sort,
and shell sort
Experimental
In this lab session we will enhance singly-linked lists with another feature: we’ll make them
circular. And, as was the case in the previous lab session, we will show how to implement creation,
insertion, and removal of nodes.
PreLab
Reading
• How many self referential pointers are used in circular single linked list?
Written
Software Needed
Python 3.7.3
Python Jupyter Notebook
Background
A circular singly linked list is a singly linked list which has the last element linked to the first element
in the list. Being circular it really has no ends; then we’ll use only one pointer pNode to indicate one
Page 38
element in the list – the newest element. Figure 2.1 show a model of such a list. pNode
(i) Creation
Init-circular-inked-list(key) z= new node z.data=key z.next=z c=new circular-linked-list c.last=z re-
turn c
(ii) Insertion
Insert-after(n,a) n.next=a.next a.next=n insert-at-last(L,n) n.next=L.last.next L.last.next=n L.last=n
(iii) Deletion
Delete(L,n) temp=L.last while temp.next!=n temp=temp.next if n==L.last: if n.next==n: L.last=NULL
else: else: ttemp.next=n.next L.last=temp temp.next=n.next
(iv) Traversal
Node temp = this.last; print temp.data temp = temp.next;
while(temp != this.last) print temp.data temp = temp.next
Procedure
a. Create:
Open a new file in Python shell, write a program and save the program with .py extension.
b. Execute:
Program logic:
c l a s s Node :
Page 39
d e f i n i t ( s e l f , data ) : s e l f . next=None s e l f . data=data p r i n t ( ” Node c r e a t e d ” , data )
c l a s s CLList :
def i n i t ( s e l f ) :
s e l f . head=None
s e l f . c t r =0
d e f i n s e r t _ b e g ( s e l f , data ) :
node=Node ( data )
i f s e l f . head==None :
s e l f . head=node
node . next= s e l f . head
else :
temp= s e l f . head
w h i l e temp . next i s not s e l f . head :
temp=temp . next
temp . next=node node . next= s e l f . head
s e l f . head=node
p r i n t ( ” Node i n s e r t e d ” , data ) s e l f . c t r+=1
return
d e f i n s e r t _ e n d ( s e l f , data ) :
node=Node ( data )
i f s e l f . head==None :
s e l f . head=node
node . next= s e l f . head
else :
temp= s e l f . head
w h i l e temp . next i s not s e l f . head :
temp=temp . next
temp . next=node node . next= s e l f . head
s e l f . c t r+=1
p r i n t ( ” Node i n s e r t e d ” , data ) r e t u r n
d e f i n s e r t _ i n t e r ( s e l f , pos , data ) : node=Node ( data )
i f pos <1 o r pos> s e l f . c t r :
print (” i n v a l i d p o s i t i o n ”)
else :
temp= s e l f . head i =1
w h i l e i <pos :
temp=temp . next i+=1
node . next=temp . next
temp . next=node s e l f . c t r+=1
p r i n t ( ” Node I n s e r e d ” , data )
return
def delete_beg ( s e l f ) :
i f s e l f . head==None :
p r i n t ( ”No Nodes e x i s t ” )
e l i f s e l f . c t r ==1:
p r i n t ( ” Node d e l e t e d ” , s e l f . head . data ) s e l f . head=None
s e l f . c t r −=1 e l s e :
p r i n t ( ” Node d e l e t e d ” , s e l f . head . data ) temp= s e l f . head
w h i l e temp . next i s not s e l f . head : temp=temp . next
s e l f . head= s e l f . head . next temp . next= s e l f . head s e l f . c t r −=1
return
Page 40
def delete_end ( s e l f ) :
i f s e l f . head==None :
p r i n t ( ”No Nodes e x i s t ” ) e l i f s e l f . c t r ==1:
p r i n t ( ” Node d e l e t e d ” , s e l f . head . data ) s e l f . head=None
s e l f . c t r −=1 e l s e :
temp= s e l f . head prev=temp
w h i l e temp . next i s not s e l f . head :
prev=temp
temp=temp . next
p r i n t ( ” Node d e l e t e d ” , temp . data ) prev . next=temp . next
s e l f . c t r −=1 r e t u r n
d e f d e l e t e _ i n t e r ( s e l f , pos ) :
i f s e l f . head==None :
p r i n t ( ”No nodes e x i s t ” )
e l i f pos <1 o r pos> s e l f . c t r :
print (” Invalid p o s i t i o n ”)
e l i f s e l f . c t r ==1:
p r i n t ( ” Node d e l e t e d ” , s e l f . head . data )
s e l f . head=None
s e l f . c t r −=1 e l s e :
temp= s e l f . head prev=temp
i =0
w h i l e i <pos :
prev=temp temp=temp . next i+=1
prev . next=temp . next
p r i n t ( ” Node d e l e t e d ” , temp . data ) s e l f . c t r −=1
return
d e f t r a v e r s e ( s e l f ) : temp= s e l f . head i =0
while i<s e l f . c t r :
p r i n t ( temp . data )
temp=temp . next i+=1
return
d e f Menu ( ) :
p r i n t ( ” 1 . I n s e r t a t b e g i n n i n g ” ) p r i n t ( ” 2 . I n s e r t a t middle ” ) p r i n t ( ” 3 . I n s e r t a t end ” )
r e t u r n ch
c=CLList ( )
p r i n t ( ” ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ C i r c u l a r Linked L i s t ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ” )
w h i l e True :
ch=Menu ( ) i f ch==1:
data=i n p u t ( ” Enter data : ” ) c . i n s e r t _ b e g ( data )
e l i f ch==2: data=i n p u t ( ” Enter a t a : ” )
pos=i n t ( i n p u t ( ” Enter p o s i t i o n : ” ) ) c . i n s e r t _ i n t e r ( pos , data )
e l i f ch==3: data=i n p u t ( ” Enter data : ” ) c . i n s e r t _ e n d ( data )
e l i f ch==4: c . d e l e t e _ b e g ( )
e l i f ch==5:
pos=i n t ( i n p u t ( ” Enter p o s i t i o n : ” ) ) c . d e l e t e _ i n t e r ( pos )
e l i f ch==6: c . d e l e t e _ e n d ( )
e l i f ch==7:
c . t r a v e r s e ( ) e l i f ch==8:
p r i n t ( ” Number o f Nodes ” , c . c t r ) e l s e :
p r i n t (” Exit ”)
Page 41
break \\
OUTPUT
insertion sort
• Lauren has a chart of distinct projected prices for a house over the next several years. She must
buy the house in one year and sell it in another, and she must do so at a loss. She wants to
minimize her financial loss. Example prince=20,15,8,2,12
Her minimum loss is incurred by purchasing in year 2 at price[1]=15 and reselling in year 5 at
price[4]=12 . Return 15-12=3 .
VIVA QUESTIONS
Page 42
Week 8 Implementation of Double Linked List
Introduction
This lab session is intended to help you develop the operations on doubly-linked lists. A doubly-linked
list is a (dynamically allocated) list where the nodes feature two relationships: successor and prede-
cessor. A model of such a list is given in figure 3.1. The type of a node in a doubly-linked list may be
defined as follows:
Objectives
Educational
• Learn to arrangement of data in the memory in the best possible way such that if somebody
needs some data, one can find it easily in the quickest time.
• Learn to rearrange the data in memory so that the Memory consumed by the data is minimum.
• To be able to explain and implement selection sort, bubble sort, merge sort, quick sort, insertion
sort, and shell sort
Experimental
• This lab session is intended to help you develop the operations on doubly-linked lists.
• This lab session is intended to help you develop the operations on doubly-linked lists like
• (i) Creation (ii) insertion (iii) deletion (iv) traversal in both ways.
PreLab
Reading
Written
Software Needed
Page 43
Figure 1: Figure 1 :
• Python 3.7.3
Background
Doubly linked list is a type of linked list in which each node apart from storing its data has two links.
The first link points to the previous node in the list and the second link points to the next node in
the list. The first node of the list has its previous link pointing to NULL similarly the last node of
the list has its next node pointing to NULL.
The two links help us to traverse the list in both backward and forward direction. But storing an
extra link requires some extra space.
1. The prev pointer of first node will always be NULL and next will point to front.
2. If the node is inserted is the first node of the list then we make front and end point to this node.
3. Else we only make front point to this node.
Insert Data before a Node: Insert Data in the end: Remove a Node:
Procedure
Page 44
a. Create:
Open a new file in Python shell, write a program and save the program with .py extension.
b. Execute:
Go to Run -> Run module (F5)
Program logic:
• Creation
• Insertion
• Deletion
• Creation
• Insertion
• Deletion
\ t e x t b f { c l a s s Node : }
d e f i n i t ( s e l f , data ) : s e l f . data=data s e l f . next= s e l f . prev=None
c l a s s DLinkedList : d e f i n i t ( s e l f ) :
s e l f . head=None s e l f . c t r =0
d e f i n s e r t _ b e g ( s e l f , data ) : node=Node ( data )
i f s e l f . head==None : s e l f . head=node
else :
node . next= s e l f . head s e l f . head . prev=node s e l f . head=node
s e l f . c t r +=1
p r i n t ( ” Nodes i n s e r t e d ” , data )
return
d e f i n s e r t −end ( s e l f , data ) : node=Node ( data )
i f s e l f . head==None : s e l f . head=node
else :
temp= s e l f . head
w h i l e ( temp . next i s not None ) :
temp=temp . next temp . next=node node . prev=temp
s e l f . c t r +=1
p r i n t ( ” Node i n s e r t e d ” , data )
return
d e f d e l e t e −beg ( s e l f ) :
i f s e l f . head==None
p r i n t ( ”No node e x i s t ” ) e l s e :
p r i n t ( ” Node d e l e t e d ” , s e l f . head . data )
s e l f . head= s e l f . head . next
s e l f . head . prev=None
Page 45
s e l f . c t r −=1
return
def delete_end ( s e l f ) :
i f s e l f . head==None :
p r i n t ( ”No nodes e x i s t ” )
e l i f s e l f . c t r ==1:
s e l f . c t r =0
p r i n t ( ” Node d e l e t e d ” , s e l f . head . data )
s e l f . head=None
else :
temp= s e l f . head
w h i l e temp . next i s not None : temp=temp . next
p r i n t ( ” Node d e l e t e d ” , temp . data )
temp=temp . prev
temp . next=None
s e l f . c t r −=1 r e t u r n
d e f i n s e r t −pos ( s e l f , pos , data ) :
i f pos==0:
s e l f . i n s e r t −beg ( data )
e l i f pos==s e l f . c t r :
s e l f . i n s e r t −end ( data )
else :
node=Node ( data )
temp= s e l f . head
i =1
w h i l e i <pos −1:
temp=temp . next i +=1
node . next=temp . next
temp . next . prev=node
temp . next=node
node . prev=temp
s e l f . c t r +=1
p r i n t ( ” Node i n s e r t e d ” , data ) r e t u r n
d e f d e l e t e _ p o s ( s e l f , pos ) :
i f s e l f . head==None :
p r i n t ( ” Node i s empty ” )
else :
i f pos==0:
s e l f . delete_beg ()
e l i f pos==s e l f . c t r :
s e l f . delete_end ( )
else :
temp= s e l f . head
i =0
w h i l e i <pos :
temp=temp . next i+=1
p r i n t ( ” node d e l e t e d ” , temp . data )
temp . prev . next=temp . next
temp . next . prev=temp . prev
temp . next=None
temp . p r e v e=None
s e l f . c t r −=1
Page 46
return
def traverse_f ( s e l f ) :
i f s e l f . head==None : p r i n t ( ”No nodes e x i s t ” )
temp= s e l f . head i =0
w h i l e i < s e l f . c t r : p r i n t ( temp . data ) temp=temp . next i+=1
return
def traverse_r ( s e l f ) :
i f s e l f . head==None : p r i n t ( ”No nodes e x i s t ” )
temp= s e l f . head
w h i l e temp . next i s not None : temp=temp . next
w h i l e temp i s not None : p r i n t ( temp . data ) temp=temp . prev
d e f menu ( ) :
p r i n t ( ” 1 . I n s e r t at beginning ”)
p r i n t ( ” 2 . I n s e r t at p o s i t i o n ”)
p r i n t ( ” 3 . I n s e r t a t end ” )
p r i n t ( ” 4 . Delete at beginning ”)
p r i n t ( ” 5 . Delete at p o s i t i o n ”)
p r i n t ( ” 6 . D e l e t e a t end ” )
p r i n t ( ” 7 . Count no o f nodes ” )
p r i n t ( ” 8 . Traverse forward ”)
print ( ” 9 . Traverse r e v e r s e ”)
p r i n t ( ” 1 0 . Quit ” )
ch=e v a l ( i n p u t ( ” Enter c h o i c e : ” ) )
r e t u r n ch
p r i n t ( ” ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ Double l i n k e d l i s t ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ” )
d=DLinkedList ( )
w h i l e True :
ch=menu ( )
i f ch==1:
data=e v a l ( i n p u t ( ” Enter data : ” ) )
d . i n s e r t −beg ( data )
e l i f ch==2:
data=e v a l ( i n p u t ( ” Enter data : ” ) )
pos=i n t ( i n p u t ( ” Enter p o s i t i o n : ” ) ) d . i n s e r t −pos ( pos , data )
e l i f ch==3:
data=e v a l ( i n p u t ( ” Enter data : ” ) )
d . i n s e r t −end ( data )
e l i f ch==4:
d . d e l e t e −beg ( )
e l i f ch==5:
pos=i n t ( i n p u t ( ” Enter p o s i t i o n : ” ) )
d . d e l e t e −pos ( pos )
e l i f ch==6:
d . d e l e t e −end ( )
e l i f ch==7:
p r i n t ( ” Number o f nodes ” , d . c t r )
e l i f ch==8:
d . t r a v e r s −f ( )
e l i f ch==9:
d . t r a v e r s e −r ( )
else :
Page 47
Figure 2: Figure 1 :
p r i n t (” Exit ”)
break
OUTPUT
PROBING FURTHER QUESTIONS
• Given pointers to the head nodes of linked lists that merge together at some point, find the node
where the two lists merge. The merge point is where both lists point to the same node, i.e. they
reference the same memory location. It is guaranteed that the two head nodes will be different,
and neither will be NULL. If the lists share a common node, return that node’s value.
• You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes
of the linked lists to check if they are equal. If all data attributes are equal and the lists are the
same length, return . Otherwise, return .
VIVA QUESTIONS
Page 48
Week - 9 Implementation of Stack Using Linked List
Introduction
Implement a stack using single linked list concept. all the single linked list operations perform based
on Stack operations LIFO(last in first out) and with the help of that knowledge we are going to
implement a stack using single linked list. using single linked lists so how to implement here it is
linked list means what we are storing the information in the form of nodes and we need to follow the
stack rules and we need to implement using single linked list nodes so what are the rules we need to
follow in the implementation of a stack a simple rule that is last in first out and all the operations we
should perform so with the help of a top variable only with the help of top variables are how to insert
the elements let’s see
Objectives
Write a Python script to implement Stack using linked list. By the end of this lab, the student
should learn to:
Educational
Learn to arrangement of data in the memory in the best possible way such that if somebody needs
some data, one can find it easily in the quickest time.
Learn to rearrange the data in memory so that the Memory consumed by the data is minimum.
Learn to Memory fragmentation is minimum when data is manipulated(add/remove/update).
To be able to explain and implement selection sort, bubble sort, merge sort, quick sort, insertion sort,
and shell sort
Experimental
Implement the sorting techniques to rearrange the records so that their keys are ordered accord-
ing to some well-defined ordering rule.
PreLab
a. What do you mean by stack overflow? b. What are the basic operations of a stack? c. How
to implement stack?
Written
Prior to coming to lab class, complete worksheet with complete sorting logic.
Software Needed
Python 3.7.3
Python Jupyter Notebook
Background
A stack can be easily implemented through the linked list. In stack Implementation, a stack contains
a top pointer. Which is “head” of the stack where pushing and popping items happens at the head of
the list. first node have null in link field and second node link have first node address in link field and
so on and last node address in “top” pointer. The main advantage of using linked list over an array
is that it is possible to implements a stack that can shrink or grow as much as needed. In using array
will put a restriction to the maximum capacity of the array which can lead to stack overflow. Here
each new node will be dynamically allocated. So overflow is not possible.
Page 49
Stack Operations:
push() : Insert the element into linked list nothing but which is the top node of Stack. pop() : Return
top element from the Stack and move the top pointer to the second node of linked list or Stack. peek():
Return the top element. display(): Print all element of Stack. Time Complexity: The time complexity
for all push(), pop(), and peek() operations is O(1) as we are not performing any kind of traversal
over the list. We perform all the operations through the current pointer only.
Program logic:
create() Define a ’Node’ structure with two members data and next. Define a Node pointer ’top’ and
set it to NULL. Implement the main method by displaying Menu with list of operations and make
suitable function calls in the main method.
push(value) - Inserting an element into the Stack Create a newNode with given value. Check whether
stack is Empty (top == NULL) If it is Empty, then set newNode → next = NULL. If it is Not Empty,
then set newNode → next = top. Finally, set top = newNode.
pop() - Deleting an Element from a Stack Check whether stack is Empty (top == NULL). If it is
Empty, then display ”Stack is Empty!!! Deletion is not possible!!!” and terminate the function If it
is Not Empty, then define a Node pointer ’temp’ and set it to ’top’. Then set ’top = top → next’.
Finally, delete ’temp’. (free(temp)).
display() - Displaying stack of elements Check whether stack is Empty (top == NULL). If it is Empty,
then display ’Stack is Empty!!!’ and terminate the function. If it is Not Empty, then define a Node
pointer ’temp’ and initialize with top. Display ’temp → data —>’ and move it to the next node.
Repeat the same until temp reaches to the first node in the stack. (temp → next != NULL). Finally!
Display ’temp → data —> NULL’.
c l a s s StackNode :
# C o n s t r u c t o r t o i n i t i a l i z e a node d e f i n i t ( s e l f , data ) :
s e l f . data = data s e l f . next = None
Page 50
c l a s s Stack :
d e f push ( s e l f , data ) :
newNode = StackNode ( data ) newNode . next = s e l f . r o o t s e l f . r o o t = newNode
p r i n t (”%d pushed t o s t a c k ” %(data ) )
d e f pop ( s e l f ) :
i f ( s e l f . isEmpty ( ) ) : r e t u r n f l o a t (”− i n f ” )
temp = s e l f . r o o t s e l f . r o o t = s e l f . r o o t . next popped = temp . data r e t u r n popped
d e f peek ( s e l f ) :
i f s e l f . isEmpty ( ) : r e t u r n f l o a t (”− i n f ” )
r e t u r n s e l f . r o o t . data
Page 51
Week -10 Implementation of Queue Using Linked List
Introduction
The major problem with the queue implemented using an array is, it will work for an only fixed
number of data values. That means, the amount of data must be specified at the beginning itself.
Queue using an array is not suitable when we don’t know the size of data which we are going to
use. A queue data structure can be implemented using a linked list data structure. The queue which
is implemented using a linked list can work for an unlimited number of values. That means, queue
using linked list can work for the variable size of data (No need to fix the size at the beginning of the
implementation). The Queue implemented using linked list can organize as many data values as we
want.
Objectives
Implement a queue and allows the user to perform enqueue and dequeue operations on it. By the
end of this lab, the student should learn to:
Educational
Learn to arrangement of data in the memory in the best possible way such that if somebody needs
some data, one can find it easily in the quickest time.
Learn to rearrange the data in memory so that the Memory consumed by the data is minimum.
Learn to Memory fragmentation is minimum when data is manipulated(add/remove/update).
To be able to explain and implement selection sort, bubble sort, merge sort, quick sort, insertion sort,
and shell sort
Experimental
Implement the sorting techniques to rearrange the records so that their keys are ordered accord-
ing to some well-defined ordering rule.
PreLab
Students practice on single linked list must before moving do following: a. Which principle is
followed in queue? b. What are the applications of queue?
Written
Prior to coming to lab class, complete worksheet with complete sorting logic.
Software Needed
Python 3.7.3
Python Jupyter Notebook
Background
In a Queue data structure, we maintain two pointers, front and rear. The front points the first item
of queue and rear points to last item. enQueue() This operation adds a new node after rear and
moves rear to the next node. deQueue() This operation removes the front node and moves front to
the next node Operations To implement queue using linked list, we need to set the following things
before implementing actual oper ations.
• Step 1 - Include all the header files which are used in the program. And declare all the user
defined functions.
Page 52
• Step 2 - Define a ’Node’ structure with two members data and next.
• Step 3 - Define two Node pointers ’front’ and ’rear’ and set both to NULL.
• Step 4 - Implement the main method by displaying Menu of list of operations and make suitable
function calls in the main method to perform user selected operation. enQueue(value) - Inserting
an element into the Queue
We can use the following steps to insert a new node into the queue...
• Step 1 - Create a newNode with given value and set ’newNode → next’ to NULL.
• Step 4 - If it is Not Empty then, set rear → next = newNode and rear = newNode.
deQueue() - Deleting an Element from Queue We can use the following steps to delete a node from
the queue...
• Step 2 - If it is Empty, then display ”Queue is Empty!!! Deletion is not possible!!!” and terminate
from the function
• Step 3 - If it is Not Empty then, define a Node pointer ’temp’ and set it to ’front’.
• Step 4 - Then set ’front = front → next’ and delete ’temp’ (free(temp)).
display() - Displaying the elements of Queue We can use the following steps to display the elements
(nodes) of a queue.
• Step 2 - If it is Empty then, display ’Queue is Empty!!!’ and terminate the function.
• Step 3 - If it is Not Empty then, define a Node pointer ’temp’ and initialize with front.
• Step 4 - Display ’temp → data —>’ and move it to the next node. Repeat the same until ’temp’
reaches to ’rear’ (temp → next != NULL).
Page 53
Figure 3: bubble sort
Stack Operations:
push() : Insert the element into linked list nothing but which is the top node of Stack. pop() : Return
top element from the Stack and move the top pointer to the second node of linked list or Stack. peek():
Return the top element. display(): Print all element of Stack. Time Complexity: The time complexity
for all push(), pop(), and peek() operations is O(1) as we are not performing any kind of traversal
over the list. We perform all the operations through the current pointer only.
Program logic:
a. Create :
Open a new file in Python shell, write a program and save the program with .py extension. b. Execute
:
Go to Run -> Run module (F5)
Source Code:
Page 54
c l a s s Node :
d e f i n i t ( s e l f , data ) : s e l f . data=data s e l f . next=None
c l a s s Queue :
d e f i n i t ( s e l f ) : s e l f . f r o n t=None s e l f . c t r =0
s e l f . r e a r=None
d e f Enqueue ( s e l f , data ) : node=Node ( data )
i f s e l f . f r o n t==None : s e l f . f r o n t=node s e l f . r e a r=node
else :
s e l f . r e a r . next=node s e l f . r e a r=node
p r i n t ( ” Node enqueued t o queue ” , data ) s e l f . c t r+=1
return
d e f Dequeue ( s e l f ) :
i f s e l f . f r o n t==None : p r i n t ( ”No Nodes e x i s t ” )
else :
p r i n t ( ” Dequeued from queue ” , s e l f . f r o n t . data ) s e l f . f r o n t= s e l f . f r o n t . next
s e l f . c t r −=1 r e t u r n
def Traverse ( s e l f ) :
i f s e l f . f r o n t==None :
p r i n t ( ”No Nodes e x i s t ” )
return
temp= s e l f . f r o n t
w h i l e temp i s not None : p r i n t ( temp . data ) temp=temp . next
d e f Menu ( ) :
p r i n t ( ” 1 . Enqueue \n2 . Dequeue \n3 . T r a v e r s e \n4 . Number o f nodes \n5 . E x i t ” ) ch=i n t ( i n p u t ( ”
r e t u r n ch
p r i n t ( ” ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ Queue ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ” )
s=Queue ( )
w h i l e True : ch=Menu ( )
i f ch==1:
data=i n p u t ( ” Enter data : ” ) s . Enqueue ( data )
e l i f ch==2: s . Dequeue ( )
e l i f ch==3: s . T r a v e r s e ( )
e l i f ch==4:
p r i n t ( ” Number o f nodes ” , s . c t r )
else :
p r i n t ( ' Quit ' )
break
OUTPUT
Page 55
• Where priority queues are used?
• What is DEQUE?
VIVA QUESTIONS
Page 56
Week -11 Graph Traversal Techniques
Introduction
Graph traversal is a technique used for searching a vertex in a graph. The graph traversal is also used
to decide the order of vertices is visited in the search process. A graph traversal finds the edges to be
used in the search process without creating loops. That means using graph traversal we visit all the
vertices of the graph without getting into looping path.
Objectives
Upon completion of this lab students will be able to: Implement some graph representation methods
and graph traversals. Write a Python script to implement depth first search Write a Python script to
implement breadth first search
By the end of this lab, the student should learn to:
Educational
Learn to arrangement of data in the memory in the best possible way such that if somebody needs
some data, one can find it easily in the quickest time.
Learn to rearrange the data in memory so that the Memory consumed by the data is minimum.
Learn to Memory fragmentation is minimum when data is manipulated(add/remove/update).
To be able to explain and implement selection sort, bubble sort, merge sort, quick sort, insertion sort,
and shell sort
Experimental
Implement the sorting techniques to rearrange the records so that their keys are ordered accord-
ing to some well-defined ordering rule.
PreLab
• What is graph?
Written
Prior to coming to lab class, complete worksheet with complete sorting logic.
Software Needed
Python 3.7.3
Python Jupyter Notebook
Background
Graph traversal is a technique used for searching a vertex in a graph. The graph traversal is also used
to decide the order of vertices is visited in the search process. A graph traversal finds the edges to be
used in the search process without creating loops. That means using graph traversal we visit all the
Page 57
vertices of the graph without getting into looping path. There are two graph traversal techniques and
they are as follows.
BFS traversal of a graph produces a spanning tree as final result. Spanning Tree is a graph without
loops. We use Queue data structure with maximum size of total number of vertices in the graph to
implement
BFS traversal:
• Step 2 - Select any vertex as starting point for traversal. Visit that vertex and insert it into the
Queue.
• Step 3 - Visit all the non-visited adjacent vertices of the vertex which is at front of the Queue
and insert
• them into the Queue. Step 4 - When there is no new vertex to be visited from the vertex which
is at front of the Queue then delete that vertex.
• Step 6 - When queue becomes empty, then produce final spanning tree by removing unused edges
from the graph
Stack Operations:
push() : Insert the element into linked list nothing but which is the top node of Stack. pop() : Return
top element from the Stack and move the top pointer to the second node of linked list or Stack. peek():
Return the top element. display(): Print all element of Stack. Time Complexity: The time complexity
for all push(), pop(), and peek() operations is O(1) as we are not performing any kind of traversal
over the list. We perform all the operations through the current pointer only.
Page 58
Figure 4: bubble sort
Program logic:
Create(): Define a ’Node’ structure with two members data and next. Define two Node pointers
’front’ and ’rear’ and set both to NULL. Implement the main method by displaying Menu of list of
operations and make suitable function calls in the main method to perform user selected operation.
enQueue(value) - Inserting an element into the Queue Create a newNode with given value and set
’newNode → next’ to NULL. Check whether queue is Empty (rear == NULL) If it is Empty then,
set front = newNode and rear = newNode. If it is Not Empty then, set rear → next = newNode and
rear = newNode. deQueue() - Deleting an Element from Queue Check whether queue is Empty (front
== NULL). If it is Empty, then display ”Queue is Empty!!! Deletion is not possible!!!” and terminate
from the function If it is Not Empty then, define a Node pointer ’temp’ and set it to ’front’. Then set
’front = front → next’ and delete ’temp’ (free(temp)).
display() - Displaying the elements of Queue Check whether queue is Empty (front == NULL). If it is
Empty then, display ’Queue is Empty!!!’ and terminate the function. If it is Not Empty then, define
a Node pointer ’temp’ and initialize with front. Display ’temp → data —>’ and move it to the next
node. Repeat the same until ’temp’ reaches to ’rear’ (temp → next != NULL). Finally! Display ’temp
→ data —> NULL’.
Procedure:
a. Create : Open a new file in Python shell, write a program and save the program with .py extension.
b. Execute : Go to Run -> Run module (F5)
Source Code:
c l a s s Node :
d e f i n i t ( s e l f , data ) : s e l f . data=data s e l f . next=None
c l a s s Queue :
d e f i n i t ( s e l f ) : s e l f . f r o n t=None s e l f . c t r =0
s e l f . r e a r=None
d e f Enqueue ( s e l f , data ) : node=Node ( data )
i f s e l f . f r o n t==None : s e l f . f r o n t=node s e l f . r e a r=node
else :
s e l f . r e a r . next=node s e l f . r e a r=node
Page 59
p r i n t ( ” Node enqueued t o queue ” , data ) s e l f . c t r+=1
return
d e f Dequeue ( s e l f ) :
i f s e l f . f r o n t==None : p r i n t ( ”No Nodes e x i s t ” )
else :
p r i n t ( ” Dequeued from queue ” , s e l f . f r o n t . data ) s e l f . f r o n t= s e l f . f r o n t . next
s e l f . c t r −=1 r e t u r n
def Traverse ( s e l f ) :
i f s e l f . f r o n t==None :
p r i n t ( ”No Nodes e x i s t ” )
return
temp= s e l f . f r o n t
w h i l e temp i s not None : p r i n t ( temp . data ) temp=temp . next
d e f Menu ( ) :
p r i n t ( ” 1 . Enqueue \n2 . Dequeue \n3 . T r a v e r s e \n4 . Number o f nodes \n5 . E x i t ” ) ch=i n t ( i n p u t ( ”
r e t u r n ch
p r i n t ( ” ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ Queue ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ” )
s=Queue ( )
w h i l e True : ch=Menu ( )
i f ch==1:
data=i n p u t ( ” Enter data : ” ) s . Enqueue ( data )
e l i f ch==2: s . Dequeue ( )
e l i f ch==3: s . T r a v e r s e ( )
e l i f ch==4:
p r i n t ( ” Number o f nodes ” , s . c t r )
else :
p r i n t ( ' Quit ' )
break \\
OUTPUT
• In class, we studied binary search trees that do not allow us to insert duplicate elements. How-
ever, sometimes we do need to store duplicates. For example, a database of student marks might
contain one record for every mark by every student; so if you’ve taken two courses, there will be
two records with the same key (your student number) and different data (your two marks). To
accomplish this, we might use a data structure called a “BST with duplicates”, or BSTD.
• List the elements of T1 in pre-order. Write a node as (key, data). Remember that the order of
nodes is determined by the key value, not by the data value. Within a “same” sequence, proceed
from top to bottom.
• Complete the function in the editor below, which has parameter: a pointer to the root of a binary
tree. It must print the values in the tree’s preorder traversal as a single line of space-separated
values.
Page 60
• You are given a pointer to the root of a binary search tree and values to be inserted into the
tree. Insert the values into their appropriate position in the binary search tree and return the
root of the updated binary tree. You just have to complete the function.
VIVA QUESTIONS
• Write a recursive program, for traversing a binary tree in preorder, inorder and postorder?
• Compose a non-recursive program, for traversing a binary tree in preorder, inorder and pos-
torder?
Page 61