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

Ds Data Structure Lab Manual

This document is a lab manual for a data structures laboratory course. It provides information on course goals, student and instructor responsibilities, lab policies, and grading. It outlines 10 weeks of lab experiments covering topics like searching techniques, sorting techniques, implementation of stacks, queues, linked lists, graphs, and their applications. The goal of the course is for students to design and analyze fundamental data structures and apply them to solve real-world problems.

Uploaded by

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

Ds Data Structure Lab Manual

This document is a lab manual for a data structures laboratory course. It provides information on course goals, student and instructor responsibilities, lab policies, and grading. It outlines 10 weeks of lab experiments covering topics like searching techniques, sorting techniques, implementation of stacks, queues, linked lists, graphs, and their applications. The goal of the course is for students to design and analyze fundamental data structures and apply them to solve real-world problems.

Uploaded by

MALLIKARJUN Y
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

INSTITUTE OF AERONAUTICAL ENGINEERING

(Autonomous)
Dundigal, Hyderabad - 500 043

Lab Manual:

DATA STRUCTURES LABORATORY (ACSC10)

Prepared by
Mr. Y.Mallikarjun (IARE10990)

Department of Computer Science and Engineering (data science)


Institute of Aeronautical Engineering
Oct 10, 2022
Contents
1. Course Information ..................... 3
Introduction ..................... 3
Student Responsibilities ..................... 3
Laboratory Teaching faculty Responsibilities ..................... 3
FacultyCoordinator Responsibilities ..................... 3
Lab Policy and Grading ..................... 3
Use of Laboratory Instruments ..................... 3
Instrument Protection Rules ..................... 1
2. Data Recording and Reports ..................... 5
3. The Laboratory Notebook ..................... 5
4. Course Goals and Objectives ..................... 5
5. The Lab Report ..................... 6
Formatting and style ..................... 6
Order of Lab Report Components ..................... 6
Coverpage ..................... 6
Objective ..................... 6
Software Used ..................... 6
6. Conclutions ..................... 7

Week 1 - SEARCHING TECHNIQUES ..................... 8


Week 2 - SORTING TECHNIQUES ..................... 12
Week 3 - SORTING TECHNIQUES ..................... 16
Week 4 - IMPLEMENTATION OF STACK AND QUEUE ..................... 29
Week 5 - APPLICATIONS OF STACK ..................... 33
Week 6 - IMPLEMENTATION OF SINGLE LINKED LIST ..................... 36
Week 7 - IMPLEMENTATION OF CIRCULAR SINGLE LINKED LIST ..................... 40
Week 8 - IMPLEMENTATION OF DOUBLE LINKED LIST ..................... 44
Week 9 - IMPLEMENTATION OF STACK USING LINKED LIST ..................... 49
Week 10 - IMPLEMENTATION OF QUEUE USING LINKED LIST ..................... 54
Week11 - GRAPH TRAVERSAL TECHNIQUES ..................... 59

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.

1.2 Student Responsibilities

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.

1.3 Laboratory Faculty Responsibilities

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.4 Faculty Coordinator Responsibilities


The faculty coordinator should ensure that the Data Structure laboratory is properly arranged. The
coordinator is responsible for supervising the teaching assistants and resolving any questions or prob-
lems that are identified by the teaching assistants or the students. The coordinator may supervise the
format of the final exam for the lab. They are also responsible for making any necessary corrections
to this manual and ensuring that it is continually updated and available.

1.5 Lab Policy and Grading


Thestudentshouldunderstandthefollowingpolicy:

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.

1.8 Grading Policy:

The final grade of this course is determined using the criterion detailed in thesyllabus.

1.9 Instructions to Students

• Before entering the lab the student should carry the following things (MANDATORY)

– Identity card issued by the college.


– Work Sheets

• 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.

• All students must follow a Dress Code while in the laboratory

• Foods, drinks are NOT allowed.

• All bags must be left at the indicated place.

• Refer to the lab staff if you need any help in using the lab.

• Respect the laboratory and its other users.

• Workspace must be kept clean and tidy after experiment is completed.

• Read the Manual carefully before coming to the laboratory and be sure about what you are
supposed to do.

• Do the experiments as per the instructions given in the manual.

• 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.

• Lab records need to be submitted on or before the date of submission.

• 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 Course Goals and Objectives

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:

Students will try to learn:

• 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.

3 Data Recording and Reports

3.1 The Laboratory Note book

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.

3.2 The 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.

3.3 Formatting and Style

• Thelabreportshallbetypedinawordprocessor. All page margins must be 1.25 inches.All content


(including text, figures, tables, etc.)must fitwithinthemargins.

• 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.4 Order of Lab Report Components

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.

3.5.3 Software Used


, Indicate which software was used in performing the experiment.

3.6 For each part of the LAB:

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.

• Thirdly,explainyourfindings. This is the most important partofyourreport,becausehere,you show


that you understand the experiment beyond the simple level of completing it. Explain(compare
expected results with those obtained). Analyse (analyze experimental error). Interpret(explain
your results in terms of theoretical issues and relate to your experimental objectives).All the
results should be presented even if there is any inconsistency with the theory. It should be
possible to understand what is going onby just reading through the text paragraphs, without
looking at the figures.

• 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.

Probing further Questions

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

By the end of this lab, the student should learn to:


• Write a Python script to for implementing linear search technique.

• Write a Python script to for implementing binary search technique.

• Write a Python script to for implementing Fibonacci search technique.


Software Needed

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[]

• If x matches with an element, return the index.

• If x doesn’t match with any of elements, return -1.

• The time complexity of the above algorithm is O(n).

• 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.

• Linear Search to find the element “20” in a given list of numbers


2. Binary 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:

Linear search technique:

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.

Binary search technique:

Given a sorted list of a[] of n elements, search a given element x in list.


a. Search a sorted list by repeatedly dividing the search interval in half. Begin with an
interval covering the whole list.
b. If the search key is less than the item in the middle item, then narrow the interval to
the lower half. Otherwise narrow it to the upper half.
c. Repeat the procedure until the value is found or the interval is empty.

Source Code

Linear search technique:

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:

array =[1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9]


def binary_search ( searchfor , array ) :
lowerbound=0
upperbound=l e n ( a r r a y )−1
found=F a l s e
w h i l e found==F a l s e and lowerbound<=upperbound :
midpoint =(lowerbound+upperbound ) / / 2
i f a r r a y [ midpoint]== s e a r c h f o r :
found =True
r e t u r n found
e l i f a r r a y [ midpoint ]< s e a r c h f o r :
lowerbound=midpoint+1
else :
upperbound=midpoint −1
r e t u r n found
#D r i v e r code
s e a r c h f o r=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 ? ” ) ) i f b i n a r y _ s e a r c h ( s e a r c h f o r , a r r a
p r i n t ( ” e l e m e n t found ” ) e l s e :
p r i n t ( ” e l e m e n t not found ” )
Output:

PROBING FURTHER QUESTIONS

• 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

• Define searching process?

• How many types of searching are there?

• Why binary search method is more efficient then liner search?

• What is worse case?

• What do you understand by the term “linear search is unsuccessful”?

• Efficiency of linear search?

• What is the drawback of linear search?

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

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
according 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 bubble sort?

• Define the insertion sort?

• Define the selection sort?

Written

• Prior to coming to lab class, complete worksheet with complete sorting logic.

Software Needed

• Python 3.7.3

• Python Jupyter Notebook

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

The efficiency of the sorting algorithm

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 : } \ \

def bubbleSort ( arr ) : n = len ( arr )


# T r a v e r s e through a l l a r r a y e l e m e n t s f o r i i n r a n g e ( n ) :
# Last i e l e m e n t s a r e a l r e a d y i n p l a c e f o r j i n r a n g e ( 0 , n−i −1):
# t r a v e r s e t h e a r r a y from 0 t o n−i −1
# Swap i f t h e e l e m e n t found i s g r e a t e r # than t h e next e l e m e n t
i f a r r [ j ] > a r r [ j +1] :
a r r [ j ] , a r r [ j +1] = a r r [ j +1] , a r r [ j ]
# D r i v e r code t o t e s t above
arr = [ 6 4 , 34 , 25 , 12 , 22 , 11 , 90]

bubbleSort ( arr )

print (” Sorted array i s : ” )


f o r i in range ( len ( arr ) ) :
p r i n t (”%d” %a r r [ i ] )
OUTPUT

bubble sort insertion sort selection sort


PROBING FURTHER QUESTIONS

• 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

• a. How many passes are required in selection sort?

• b. Write the time complexity of insertion sort?

• c. Write the time complexity of selection sort?

• d. Write the time complexity of bubble sort?

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

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

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”.

Step by Step Process:

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.

• Step 3 - Increment i until list[i] > pivot then stop.

• Step 4 - Decrement j until list[j] < pivot then stop.

• Step 5 - If i < j then exchange list[i] and list[j].

• Step 6 - Repeat steps 3,4 & 5 until i > j.

• Step 7 - Exchange the pivot element with list[j] element.

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:
\ 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

• How many passes are required in selection sort?

• Write the time complexity of insertion sort?

• Write the time complexity of selection sort?

• Write the time complexity of bubble sort?

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

By the end of this lab, the student should learn to:

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

To use queues for basic timing simulations.


To be able to implement the abstract data type list as a linked list using the node and reference
pattern.
To be able to compare the performance of our linked list implementation with Python’s list imple-
mentation.

PreLab

Reading

• Read and study the Background section of this Laboratory.

• What is stack?

• What are the operations performed on stack?

• How stacks are implemented?

• What are the applications of stack?

• What is recursion?

• Define “Top of stack”.

• How to implement stack?

• Define a queue?

• Define the condition “overflow”.

• Define the condition “underflow”.

• Define a queue.

• Which principle is followed in 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 and its operations using list:

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 ”)

Queue and its operations using list:

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

Stack and its operations using list:

Page 23
Stack and its operations using list:

Queue and its operations using list:


PROBING FURTHER QUESTIONS

• 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

• Write the time complexity of PUSH operation?

• Write the time complexity of POP operation?

• List out the applications of stack?

• How to remove an element from stack?

• How to insert an element into a stack?

• Write the time complexity to insert an element into a queue?

• Write the time complexity to delete an element from a queue?

• List out the advantage of circular queue over linear queue?

• Define a priority queue?

Page 25
Week -5 Applications of Stack

Introduction

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 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

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

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

• Read and study the Background section of this Laboratory.

• What is an expression?

• Which operator is having highest priority?

• Give an example for prefix expression?

• Give an example for postfix expression?

Written

Prior to coming to lab class, complete worksheet with complete sorting logic.

Software Needed

• Python 3.7.3

• Python Jupyter Notebook

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:

Go to Run -> Run module (F5)

Program logic:

Infix expression to postfix expression:

Page 27
Let, X is an arithmetic expression written in infix notation. This algorithm finds the equivalent postfix
expression Y.

• 1. Push “(“onto Stack, and add “)” to the end of X.

• 2. Scan X from left to right and repeat Step 3 to 6 for each element of X until the Stack is
empty.

• 3. If an operand is encountered, add it to Y.

• 4. If a left parenthesis is encountered, push it onto Stack.

• 5. If an operator is encountered ,then:

• – 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]

• 6. If a right parenthesis is encountered ,then:

– 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.

Evaluation of the postfix expression:

• 1. Create a stack to store operands (or values).

• 2. Scan the given expression and do following for every scanned element.

• 1. If the element is a number, push it into the stack

• 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

Evaluation of the postfix expression:


# 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 = [ ]
# 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 ( )
else :
return ”$”
# 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 )

OUTPUT

Page 29
Infix expression to postfix expression:

Evaluation of the postfix expression:

PROBING FURTHER QUESTIONS

• 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

a. What is the output of the following expression: 2 3 4 5 + * -


b. What is the advantage of postfix expression?
c. What is the maximum difference between number of operators and operands?
d. Which expression doesn’t require parenthesis?
e. What is the output of the following expression: + * - 2 3 4 5

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

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

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

Prior to coming to lab class, complete Part 0 of the Procedure.


Software Needed
Python 3.7.3
Python Jupyter Notebook

Background

Page 31
Single Linked List: (i) creation (ii) insertion (iii) deletion (iv) traversal (i) Creation:

• first=new node;create the 1st node of the list pointed by first;

• Read(Data(first));

• NEXT(First)=NULL;

• Far a First; [point Far to the First]

• For I=1 to N-1 repeat steps 6 to 10

• X=new node;

• Read(Data(X))

• NEXT(X)=NULL;

• NEXT(Far)=X; connect the nodes

• Far=X;[shift the pointer to the last node of the list]

• end of For Loop

• 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.

(iii) Add first:

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.

• Update head link to point to the new node.

(iv) Add last:

In this case, new node is inserted right after the current tail node.

It can be done in two steps:

• Update the next link of the current tail node, to point to the newnode

• Update tail link to point to the newnode.

(v) General case:

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:

• Update link of the ”previous” node, to point to the new node.

• Update link of the new node, to point to the ”next” node.

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:

• Update head link to point to the node, next to thehead.

• Dispose removed node.

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.

• Set next link of the new tail to NULL.

• Dispose removed node.

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:

• If First=NULL then print “List empty” STOP;

• count=0;

• ptr=First; point ptr to the 1st node

• While ptr<> NULL repeat Steps 5 to 6

• count=count+1;

• ptr=NEXT(ptr) [shift ptr to the next node]

• print (‘Number of nodes=’, count)

• END

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:

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 count ( s e l f ) : nc=0 temp= s e l f . s t a r t


w h i l e temp!=None : nc+=1 temp=temp . next
p r i n t ( ” number o f nodes=%d” %nc ) r e t u r n nc

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 ) )

### OUTSIDE CLASS


d e f menu ( ) :
p r i n t ( ” 1 . c r e a t e l i s t \n2 . i n s e r t b e g i n \n3 . i n s e r t e n d \n4 . i n s e r t m i d \n5 . d e l e t e b e

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

PROBING FURTHER QUESTIONS

• 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

• What is the time complexity to insert a node at the beginning of linkedlist?

• What is the time complexity to traverse a linked list?

• How many modifications are required to delete a node at the beginning?

• How many modifications are required to insert a node in the middle of the linked list?

• What are the types of linked list?

• What are the applications of a 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

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

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

• What is circular linked list?

• What type of memory allocation is used in linked circular list?

• How many self referential pointers are used in circular single linked list?

• What is double linked list?

Written

Which node contains NULL pointer in a circular single linked list?


How many nodes you can have in a circular single linked list?

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

The structure of a node may be:


t y p e d e f s t r u c t nodetype
{
i n t key ; /∗ an o p t i o n a l f i e l d ∗/
/∗ o t h e r u s e f u l data f i e l d s ∗/
s t r u c t nodetype ∗ next ;
/∗ l i n k t o next node ∗/
} NodeT ; \ \
Programming Logic:

Circular Linked List:

(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:

Go to Run -> Run module (F5)

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

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

What is circular linked list?


What type of memory allocation is used in linked circular list?
How many self referential pointers are used in circular single linked list?
What is double linked list?
Which node contains NULL pointer in a circular single linked list?
How many nodes you can have in a circular single linked list?
Formulate a program to convert a single linked to circular linked list?

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

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

• 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

• a. What is double linked list

• b. How to represent a node in double linked list

• c. Differentiate between single and double linked list

Written

• What is double linked list

• How to represent a node in double linked list

• Differentiate between single and double linked list

Software Needed

Page 43
Figure 1: Figure 1 :

• Python 3.7.3

• Python Jupyter Notebook

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.

Operations on double linked list:

• add-front: Adds a new node in the beginning of list

• add-after: Adds a new node after another node

• add-before: Adds a new node before another node

• add-end: Adds a new node in the end of list

• delete: Removes the node

• forward-traverse: Traverse the list in forward direction

• backward-traverse: Traverse the list in backward direction

Insert Data in the beginning:

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

• Traversal in both ways

• Double Linked List

• Creation

• Insertion

• Deletion

• Traversal in both ways

\ 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

• How to represent double linked list?

• How will you traverse double linked list?

• List the advantages of double linked list over single list?

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 :

# Constructor to i n i t i a l i z e the root of l i n k e d l i s t


def i n i t ( s e l f ) :
s e l f . r o o t = None
d e f isEmpty ( s e l f ) :
r e t u r n True i f s e l f . r o o t i s None e l s e F a l s e

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

# D r i v e r program t o t e s t above c l a s s s t a c k = Stack ( )


s t a c k . push ( 1 0 ) s t a c k . push ( 2 0 ) s t a c k . push ( 3 0 )

p r i n t (”%d popped from s t a c k ” %( s t a c k . pop ( ) ) )


p r i n t ( ” Top e l e m e n t i s %d ” %( s t a c k . peek ( ) ) )
OUTPUT

PROBING FURTHER QUESTIONS

• How To Remove An Element From Stack?


• How To Insert An Element Using A Stack?
• Is It Possible To Store Any Number Of Data Elements In Stack?
• What Are The Demerits Of Stack?
VIVA QUESTIONS

• How to remove an element from stack?


• How to insert an element using a stack?
• Is it possible to store any number of data elements in stack?
• What are the demerits of stack?

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 2 - Check whether queue is Empty (rear == NULL)

• Step 3 - If it is Empty then, set front = newNode and rear = newNode.

• 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 1 - Check whether queue is Empty (front == NULL).

• 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 1 - Check whether queue is Empty (front == NULL).

• 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).

• Step 5 - Finally! Display ’temp → data —> 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:

Queue using linked list:


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:

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

PROBING FURTHER QUESTIONS

• What is the advantage of circular queue over linear queue?

Page 55
• Where priority queues are used?

• What is DEQUE?

VIVA QUESTIONS

• a. How to remove an element from stack?

• b. How to insert an element using a stack?

• c. Is it possible to store any number of data elements in stack?

• d. What are the demerits of stack?

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

Before moving students must refer following:

• What is graph?

• List various ways of representations of graph?

• How many graph traversal algorithms are there?

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.

• DFS (Depth First Search)

• BFS (Breadth First Search)

BFS (Breadth First Search):

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:

We use the following steps to implement BFS traversal

• Step 1 - Define a Queue of size total number of vertices in the graph.

• 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 5 - Repeat steps 3 and 4 until queue becomes empty.

• 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:

Queue using linked list:

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

PROBING FURTHER QUESTIONS

• 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

• Formulate a program to create a Binary Tree of integers?

• 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?

• Write a program to check balance property of a tree?

Page 61

You might also like