SlideShare a Scribd company logo
1 of 74
Data Structures and
Algorithms
N Radhakrishnan
Assistant Professor
Anna University, Chennai
19 July 2022 Anna University, Chennai - 600 025 2
Topics
 Revision of Previous Session
Contents
 Cursor-based Implementation of
Lists
 Stacks
 Queues
 Applications of Stacks and Queues
 Doubly Linked Lists
19 July 2022 Anna University, Chennai - 600 025 3
Cursor Implementation
Problems with linked list implementation:
 Same language do not support pointers!
• Then how can you use linked lists ?
 new and free operations are slow
• Actually not constant time
 SOLUTION: Implement linked list on an array -
called CURSOR
19 July 2022 Anna University, Chennai - 600 025 4
Cursor Implementation - Diagram
19 July 2022 Anna University, Chennai - 600 025 5
Cursor Implementation
If L = 5, then L represents list (A, B, E)
If M = 3, then M represents list (C, D, F)
19 July 2022 Anna University, Chennai - 600 025 6
Arrays - Pros and Cons
 Pros
• Directly supported by C
• Provides random access
 Cons
• Size determined at compile time
• Inserting and deleting elements is
time consuming
19 July 2022 Anna University, Chennai - 600 025 7
Linked Lists - Pros and Cons
 Pros
• Size determined during runtime
• Inserting and deleting elements is
quick
 Cons
• No random access
• User must provide programming
support
19 July 2022 Anna University, Chennai - 600 025 8
Application of Lists
 Lists can be used
 To store the records sequentially
 For creation of stacks and queues
 For polynomial handling
 To maintain the sequence of operations
for do / undo in software
 To keep track of the history of web sites
visited
19 July 2022 Anna University, Chennai - 600 025 9
How to change the direction ?
19 July 2022 Anna University, Chennai - 600 025 10
Turntable
19 July 2022 Anna University, Chennai - 600 025 11
Another Method
19 July 2022 Anna University, Chennai - 600 025 12
Stack
19 July 2022 Anna University, Chennai - 600 025 13
What is a Stack ?
 a stack is a particular kind of abstract data
type or collection in which the fundamental
(or only) operations on the collection are the
addition of an entity to the collection, known
as push and removal of an entity, known as
pop.
19 July 2022 Anna University, Chennai - 600 025 14
Basic Principle
 The relation between the push and pop
operations is such that the stack is a Last-In-
First-Out (LIFO) data structure.
 In a LIFO data structure, the last element
added to the structure must be the first one
to be removed.
19 July 2022 Anna University, Chennai - 600 025 15
Operations on Stack
 This is equivalent to the requirement that,
considered as a linear data structure, or
more abstractly a sequential collection, the
push and pop operations occur only at one
end of the structure, referred to as the top of
the stack.
 Often a peek or top operation is also
implemented, returning the value of the top
element without removing it.
19 July 2022 Anna University, Chennai - 600 025 16
Implementation
 A stack may be implemented to have a
bounded capacity. If the stack is full and
does not contain enough space to accept an
entity to be pushed, the stack is then
considered to be in an overflow state. The
pop operation removes an item from the top
of the stack. A pop either reveals previously
concealed items or results in an empty stack,
but, if the stack is empty, it goes into
underflow state, which means no items are
present in stack to be removed.
19 July 2022 Anna University, Chennai - 600 025 17
Restricted Data Structure
 A stack is a restricted data structure,
because only a small number of operations
are performed on it. The nature of the pop
and push operations also means that stack
elements have a natural order. Elements are
removed from the stack in the reverse order
to the order of their addition. Therefore, the
lower elements are those that have been on
the stack the longest.
19 July 2022 Anna University, Chennai - 600 025 18
Examples
19 July 2022 Anna University, Chennai - 600 025 19
In Simple Words
 A stack
• Last-in, first-out (LIFO) property
 The last item placed on the stack will be
the first item removed
• Analogy
 A stack of dishes in a cafeteria
 A stack of Books
 A stack of Dosa
 A stack of Money
19 July 2022 Anna University, Chennai - 600 025 20
ADT Stack
 ADT stack operations
• Create an empty stack
• Destroy a stack
• Determine whether a stack is empty
• Add a new item
• Remove the item that was added most
recently
• Retrieve the item that was added most
recently
 A program can use a stack independently
of the stack’s implementation
19 July 2022 Anna University, Chennai - 600 025 21
Stack Operations
bool isEmpty() const;
// Determines whether a stack is empty.
// Precondition: None.
// Postcondition: Returns true if the
// stack is empty; otherwise returns
// false.
19 July 2022 Anna University, Chennai - 600 025 22
Stack Operations
bool push(StackItemType newItem);
// Adds an item to the top of a stack.
// Precondition: newItem is the item to
// be added.
// Postcondition: If the insertion is
// successful, newItem is on the top of
// the stack.
19 July 2022 Anna University, Chennai - 600 025 23
Stack Operations
bool pop(StackItemType& stackTop);
// Retrieves and removes the top of a stack
// Precondition: None.
// Postcondition: If the stack is not empty,
// stackTop contains the item that was added
// most recently and the item is removed.
// However, if the stack is empty, deletion
// is impossible and stackTop is unchanged.
19 July 2022 Anna University, Chennai - 600 025 24
Stack Operations
bool getTop(StackItemType& stackTop) const;
// Retrieves the top of a stack.
// Precondition: None.
// Postcondition: If the stack is not empty,
// stackTop contains the item that was added
// most recently. However, if the stack is
// empty, the operation fails and stackTop
// is unchanged. The stack is unchanged.
19 July 2022 Anna University, Chennai - 600 025 25
Implementation Using Arrays
19 July 2022 Anna University, Chennai - 600 025 26
The Stack Class - Public Contents
class Stack
{
public:
Stack() { size = 10; current = -1;}
int pop(){ return A[current--];}
void push(int x){A[++current] = x;}
int top(){ return A[current];}
int isEmpty(){return ( current == -1 );}
int isFull(){ return ( current == size-1);}
19 July 2022 Anna University, Chennai - 600 025 27
The Stack Class - Private Contents
private:
int object; // The data element
int current; // Index of the array
int size; // max size of the array
int A[10]; // Array of 10 elements
};
19 July 2022 Anna University, Chennai - 600 025 28
Stack - a Very Simple Application
 The simplest application of a stack is to
reverse a word.
 You push a given word to stack - letter
by letter - and then pop letters from the
stack.
19 July 2022 Anna University, Chennai - 600 025 29
Applications of Stack
 Recursion
 Decimal to Binary Conversion
 Infix to Postfix Conversion and
Evaluation of Postfix Expressions
 Rearranging Railroad Cars
 Quick Sort
 Function Calls
 Undo button in various software.
19 July 2022 Anna University, Chennai - 600 025 30
outputInBinary - Algorithm
function outputInBinary(Integer n)
Stack s = new Stack
while n > 0 do
Integer bit = n modulo 2
s.push(bit)
if s is full then
return error
end if
n = floor(n / 2)
end while
while s is not empty do
output(s.pop())
end while
end function
19 July 2022 Anna University, Chennai - 600 025 31
Algebraic Expressions
 Infix expressions
• An operator appears between its operands
 Example: a + b
 Prefix expressions
• An operator appears before its operands
 Example: + a b
 Postfix expressions
• An operator appears after its operands
 Example: a b +
19 July 2022 Anna University, Chennai - 600 025 32
A complicated example
 Infix expressions:
a + b * c + ( d * e + f ) * g
 Postfix expressions:
a b c * + d e * f + g * +
 Prefix expressions:
+ + a * b c * + * d e f g
19 July 2022 Anna University, Chennai - 600 025 33
Evaluation of Postfix Expression
19 July 2022 Anna University, Chennai - 600 025 34
Evaluation of Postfix Expression
 The calculation: 1 + 2 * 4 + 3 can be written
down like this in postfix notation with the
advantage of no precedence rules and
parentheses needed
 1 2 4 * + 3 +
 The expression is evaluated from the left to
right using a stack:
• when encountering an operand: push it
• when encountering an operator: pop two
operands, evaluate the result and push it.
19 July 2022 Anna University, Chennai - 600 025 35
19 July 2022 Anna University, Chennai - 600 025 36
Infix to Postfix Conversion
19 July 2022 Anna University, Chennai - 600 025 37
What’s this ?
19 July 2022 Anna University, Chennai - 600 025 38
Queue
19 July 2022 Anna University, Chennai - 600 025 39
Queue
 A stack is LIFO (Last-In First Out) structure.
In contrast, a queue is a FIFO (First-In First-
Out ) structure.
 In a FIFO data structure, the first element
added to the queue will be the first one to be
removed.
 A queue is a linear structure for which items
can be only inserted at one end and removed
at another end.
19 July 2022 Anna University, Chennai - 600 025 40
Operations on Queue
 We will dedicate once again six operations on
the Queue.
• You can add a person to the queue (enque),
• Look who is the first person to be serviced (front)
• Rremove the first person (dequeue) and
• Check whether the queue is empty (isEmpty).
• Also there are two more operations to create and
to destroy the queue.
19 July 2022 Anna University, Chennai - 600 025 41
Operations
 Queue create()
• Creates an empty queue
 boolean isEmpty(Queue q)
• Tells whether the queue q is empty
 enqueue(Queue q, Item e)
• Place e at the rear of the queue q
 destroy(Queue q)
• destroys queue q
19 July 2022 Anna University, Chennai - 600 025 42
Operations Continued
 Item front(Queue q)
• returns the front element in Queue q
without removing it
Precondition: q is not empty
 dequeue(Queue q)
• removes front element from the queue q
Precondition: q is not empty
19 July 2022 Anna University, Chennai - 600 025 43
Implementation Using Arrays
 If we use an array to hold queue elements,
dequeue operation at the front (start) of
the array is expensive.
 This is because we may have to shift up to
“n” elements.
 For the stack, we needed only one end; for
queue we need both.
 To get around this, we will not shift upon
removal of an element.
19 July 2022 Anna University, Chennai - 600 025 44
Snapshot of a Queue
19 July 2022 Anna University, Chennai - 600 025 45
enqueue()
19 July 2022 Anna University, Chennai - 600 025 46
enqueue() again
19 July 2022 Anna University, Chennai - 600 025 47
dequeue()
19 July 2022 Anna University, Chennai - 600 025 48
dequeue() again
19 July 2022 Anna University, Chennai - 600 025 49
Two more enqueue()
19 July 2022 Anna University, Chennai - 600 025 50
What’s Wrong ?
 We have inserts and removal running in
constant time but we created a new
problem.
 We cannot insert new elements even though
there are two places available at the start of
the array.
 Solution: allow the queue to “wrap around”.
Basic idea is to picture the array as a circular
array as show below.
19 July 2022 Anna University, Chennai - 600 025 51
Queue array wrap-around
19 July 2022 Anna University, Chennai - 600 025 52
enqueue(element)
void enqueue(int x)
{
rear = (rear+1)%size;
array[rear] = x;
noElements = noElements+1;
}
19 July 2022 Anna University, Chennai - 600 025 53
dequeue()
int dequeue()
{
int x = array[front];
front = (front+1)%size;
noElements = noElements-1;
return x;
}
19 July 2022 Anna University, Chennai - 600 025 54
isEmpty() and isFull()
int isFull()
{
return noElements == size;
}
int isEmpty()
{
return noElements == 0;
}
19 July 2022 Anna University, Chennai - 600 025 55
Pointer Based Implementation
 Possible implementations of a pointer-based
queue
• A linear linked list with two external references
 A reference to the front
 A reference to the back
• A circular linked list with one external reference
 A reference to the back
19 July 2022 Anna University, Chennai - 600 025 56
Queue - Linear and Circular List
19 July 2022 Anna University, Chennai - 600 025 57
Non-empty Queue - Insertion
19 July 2022 Anna University, Chennai - 600 025 58
Empty Queue - Insertion
19 July 2022 Anna University, Chennai - 600 025 59
Queue with more than 1 element -
Deletion
19 July 2022 Anna University, Chennai - 600 025 60
Applications of Queues
 Queue is used when things don’t have to be
processed immediatly, but have to be
processed in First In First Out order like
Breadth First Search.
 This property of Queue makes it also useful
in following kind of scenarios.
19 July 2022 Anna University, Chennai - 600 025 61
Applications of Queues
 When a resource is shared among multiple
consumers. Examples include CPU
scheduling, Disk Scheduling.
 When data is transferred asynchronously
(data not necessarily received at same rate
as sent) between two processes. Examples
include IO Buffers, pipes, file IO, etc.
 Operating systems often maintain a queue
of processes that are ready to execute or
that are waiting for a particular event to
occur.
19 July 2022 Anna University, Chennai - 600 025 62
Applications of Queues
 Computer systems must often provide a
“holding area” for messages between two
processes, two programs, or even two
systems. This holding area is usually called
a “buffer” and is often implemented as a
queue.
 Call center phone systems will use a queue
to hold people in line until a service
representative is free.
19 July 2022 Anna University, Chennai - 600 025 63
Applications of Queues
 Buffers on MP3 players and portable CD
players, iPod playlist. Playlist for jukebox -
add songs to the end, play from the front of
the list.
 Round Robin (RR) algorithm is an important
scheduling algorithm. It is used especially for
the time-sharing system. The circular queue
is used to implement such algorithms.
19 July 2022 Anna University, Chennai - 600 025 64
Why Doubly Linked List ?
 given only the pointer location, we cannot access its
predecessor in the list.
 Another task that is difficult to perform on a linear
linked list is traversing the list in reverse.
 Doubly linked list A linked list in which each node is
linked to both its successor and its predecessor
 In such a case, where we need to access the node
that precedes a given node, a doubly linked list is
useful.
19 July 2022 Anna University, Chennai - 600 025 65
Doubly Linked List
 In a doubly linked list, the nodes are linked
in both directions. Each node of a doubly
linked list contains three parts:
• Info: the data stored in the node
• Next: the pointer to the following node
• Back: the pointer to the preceding node
19 July 2022 Anna University, Chennai - 600 025 66
Operations on Doubly Linked Lists
 The algorithms for the insertion and deletion
operations on a doubly linked list are
somewhat more complicated than the
corresponding operations on a singly linked
list.
 The reason is clear: There are more pointers
to keep track of in a doubly linked list.
19 July 2022 Anna University, Chennai - 600 025 67
Inserting Item
 As an example, consider the Inserting an
item.
 To link the new node, after a given node, in a
singly linked list, we need to change two
pointers:
• newNode->next and
• location->next.
 The same operation on a doubly linked list
requires four pointer changes.
19 July 2022 Anna University, Chennai - 600 025 68
Singly Linked List Insertion
19 July 2022 Anna University, Chennai - 600 025 69
Doubly Linked List Insertion
19 July 2022 Anna University, Chennai - 600 025 70
The Order is Important
19 July 2022 Anna University, Chennai - 600 025 71
Doubly Linked List - Deletion
 One useful feature of a doubly linked list is
its elimination of the need for a pointer to a
node's predecessor to delete the node.
 Through the back member, we can alter the
next member of the preceding node to make
it jump over the unwanted node.
 Then we make the back pointer of the
succeeding node point to the preceding
node.
19 July 2022 Anna University, Chennai - 600 025 72
Doubly Linked List - Deletion
19 July 2022 Anna University, Chennai - 600 025 73
Special Cases of Deletion
 We do, however, have to be careful about the
end cases:
• If location->back is NULL, we are deleting the
first node
• if location->next is NULL, we are deleting the last
node.
• If both location->back and location->next are
NULL, we are deleting the only node.
19 July 2022 Anna University, Chennai - 600 025 74
Interaction

More Related Content

Similar to dsa1.ppt

stack_presentaton_HUSNAIN[2].pojklklklptx
stack_presentaton_HUSNAIN[2].pojklklklptxstack_presentaton_HUSNAIN[2].pojklklklptx
stack_presentaton_HUSNAIN[2].pojklklklptx
HusnainNaqvi2
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
RAtna29
 
Introduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdfIntroduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdf
arpitaeron555
 

Similar to dsa1.ppt (20)

IRJET- Comparison of Stack and Queue Data Structures
IRJET- Comparison of Stack and Queue Data StructuresIRJET- Comparison of Stack and Queue Data Structures
IRJET- Comparison of Stack and Queue Data Structures
 
IGA Cable Structures
IGA Cable StructuresIGA Cable Structures
IGA Cable Structures
 
Unit I-Data structures stack & Queue
Unit I-Data structures stack & QueueUnit I-Data structures stack & Queue
Unit I-Data structures stack & Queue
 
CH4.pptx
CH4.pptxCH4.pptx
CH4.pptx
 
stacks1
stacks1stacks1
stacks1
 
stack_presentaton_HUSNAIN[2].pojklklklptx
stack_presentaton_HUSNAIN[2].pojklklklptxstack_presentaton_HUSNAIN[2].pojklklklptx
stack_presentaton_HUSNAIN[2].pojklklklptx
 
Algorithm and Data Structure - Queue
Algorithm and Data Structure - QueueAlgorithm and Data Structure - Queue
Algorithm and Data Structure - Queue
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
 
5. Queue - Data Structures using C++ by Varsha Patil
5. Queue - Data Structures using C++ by Varsha Patil5. Queue - Data Structures using C++ by Varsha Patil
5. Queue - Data Structures using C++ by Varsha Patil
 
2.1 STACK & QUEUE ADTS
2.1 STACK & QUEUE ADTS2.1 STACK & QUEUE ADTS
2.1 STACK & QUEUE ADTS
 
Data Structures by Maneesh Boddu
Data Structures by Maneesh BodduData Structures by Maneesh Boddu
Data Structures by Maneesh Boddu
 
Unit i(dsc++)
Unit i(dsc++)Unit i(dsc++)
Unit i(dsc++)
 
Week 9: Programming for Data Analysis
Week 9: Programming for Data AnalysisWeek 9: Programming for Data Analysis
Week 9: Programming for Data Analysis
 
Unit-ii-Queue ADT.pptx
Unit-ii-Queue ADT.pptxUnit-ii-Queue ADT.pptx
Unit-ii-Queue ADT.pptx
 
Stack and queue
Stack and queueStack and queue
Stack and queue
 
Introduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdfIntroduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdf
 
dsa.ppt
dsa.pptdsa.ppt
dsa.ppt
 
Difference between stack and queue
Difference between stack and queueDifference between stack and queue
Difference between stack and queue
 
2 b queues
2 b queues2 b queues
2 b queues
 
Stack in C.pptx
Stack in C.pptxStack in C.pptx
Stack in C.pptx
 

More from ssuser0be977

More from ssuser0be977 (8)

IBM list NM portal not updategbbbbbnnmhhh
IBM list NM portal not updategbbbbbnnmhhhIBM list NM portal not updategbbbbbnnmhhh
IBM list NM portal not updategbbbbbnnmhhh
 
lect23_optimization.ppt
lect23_optimization.pptlect23_optimization.ppt
lect23_optimization.ppt
 
CS540-2-lecture11 - Copy.ppt
CS540-2-lecture11 - Copy.pptCS540-2-lecture11 - Copy.ppt
CS540-2-lecture11 - Copy.ppt
 
wk1a-basicstats.ppt
wk1a-basicstats.pptwk1a-basicstats.ppt
wk1a-basicstats.ppt
 
wk1a-basicstats (2).ppt
wk1a-basicstats (2).pptwk1a-basicstats (2).ppt
wk1a-basicstats (2).ppt
 
dynamicList.ppt
dynamicList.pptdynamicList.ppt
dynamicList.ppt
 
lect08.ppt
lect08.pptlect08.ppt
lect08.ppt
 
11CS10033.pptx
11CS10033.pptx11CS10033.pptx
11CS10033.pptx
 

Recently uploaded

notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
MsecMca
 

Recently uploaded (20)

chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 

dsa1.ppt

  • 1. Data Structures and Algorithms N Radhakrishnan Assistant Professor Anna University, Chennai
  • 2. 19 July 2022 Anna University, Chennai - 600 025 2 Topics  Revision of Previous Session Contents  Cursor-based Implementation of Lists  Stacks  Queues  Applications of Stacks and Queues  Doubly Linked Lists
  • 3. 19 July 2022 Anna University, Chennai - 600 025 3 Cursor Implementation Problems with linked list implementation:  Same language do not support pointers! • Then how can you use linked lists ?  new and free operations are slow • Actually not constant time  SOLUTION: Implement linked list on an array - called CURSOR
  • 4. 19 July 2022 Anna University, Chennai - 600 025 4 Cursor Implementation - Diagram
  • 5. 19 July 2022 Anna University, Chennai - 600 025 5 Cursor Implementation If L = 5, then L represents list (A, B, E) If M = 3, then M represents list (C, D, F)
  • 6. 19 July 2022 Anna University, Chennai - 600 025 6 Arrays - Pros and Cons  Pros • Directly supported by C • Provides random access  Cons • Size determined at compile time • Inserting and deleting elements is time consuming
  • 7. 19 July 2022 Anna University, Chennai - 600 025 7 Linked Lists - Pros and Cons  Pros • Size determined during runtime • Inserting and deleting elements is quick  Cons • No random access • User must provide programming support
  • 8. 19 July 2022 Anna University, Chennai - 600 025 8 Application of Lists  Lists can be used  To store the records sequentially  For creation of stacks and queues  For polynomial handling  To maintain the sequence of operations for do / undo in software  To keep track of the history of web sites visited
  • 9. 19 July 2022 Anna University, Chennai - 600 025 9 How to change the direction ?
  • 10. 19 July 2022 Anna University, Chennai - 600 025 10 Turntable
  • 11. 19 July 2022 Anna University, Chennai - 600 025 11 Another Method
  • 12. 19 July 2022 Anna University, Chennai - 600 025 12 Stack
  • 13. 19 July 2022 Anna University, Chennai - 600 025 13 What is a Stack ?  a stack is a particular kind of abstract data type or collection in which the fundamental (or only) operations on the collection are the addition of an entity to the collection, known as push and removal of an entity, known as pop.
  • 14. 19 July 2022 Anna University, Chennai - 600 025 14 Basic Principle  The relation between the push and pop operations is such that the stack is a Last-In- First-Out (LIFO) data structure.  In a LIFO data structure, the last element added to the structure must be the first one to be removed.
  • 15. 19 July 2022 Anna University, Chennai - 600 025 15 Operations on Stack  This is equivalent to the requirement that, considered as a linear data structure, or more abstractly a sequential collection, the push and pop operations occur only at one end of the structure, referred to as the top of the stack.  Often a peek or top operation is also implemented, returning the value of the top element without removing it.
  • 16. 19 July 2022 Anna University, Chennai - 600 025 16 Implementation  A stack may be implemented to have a bounded capacity. If the stack is full and does not contain enough space to accept an entity to be pushed, the stack is then considered to be in an overflow state. The pop operation removes an item from the top of the stack. A pop either reveals previously concealed items or results in an empty stack, but, if the stack is empty, it goes into underflow state, which means no items are present in stack to be removed.
  • 17. 19 July 2022 Anna University, Chennai - 600 025 17 Restricted Data Structure  A stack is a restricted data structure, because only a small number of operations are performed on it. The nature of the pop and push operations also means that stack elements have a natural order. Elements are removed from the stack in the reverse order to the order of their addition. Therefore, the lower elements are those that have been on the stack the longest.
  • 18. 19 July 2022 Anna University, Chennai - 600 025 18 Examples
  • 19. 19 July 2022 Anna University, Chennai - 600 025 19 In Simple Words  A stack • Last-in, first-out (LIFO) property  The last item placed on the stack will be the first item removed • Analogy  A stack of dishes in a cafeteria  A stack of Books  A stack of Dosa  A stack of Money
  • 20. 19 July 2022 Anna University, Chennai - 600 025 20 ADT Stack  ADT stack operations • Create an empty stack • Destroy a stack • Determine whether a stack is empty • Add a new item • Remove the item that was added most recently • Retrieve the item that was added most recently  A program can use a stack independently of the stack’s implementation
  • 21. 19 July 2022 Anna University, Chennai - 600 025 21 Stack Operations bool isEmpty() const; // Determines whether a stack is empty. // Precondition: None. // Postcondition: Returns true if the // stack is empty; otherwise returns // false.
  • 22. 19 July 2022 Anna University, Chennai - 600 025 22 Stack Operations bool push(StackItemType newItem); // Adds an item to the top of a stack. // Precondition: newItem is the item to // be added. // Postcondition: If the insertion is // successful, newItem is on the top of // the stack.
  • 23. 19 July 2022 Anna University, Chennai - 600 025 23 Stack Operations bool pop(StackItemType& stackTop); // Retrieves and removes the top of a stack // Precondition: None. // Postcondition: If the stack is not empty, // stackTop contains the item that was added // most recently and the item is removed. // However, if the stack is empty, deletion // is impossible and stackTop is unchanged.
  • 24. 19 July 2022 Anna University, Chennai - 600 025 24 Stack Operations bool getTop(StackItemType& stackTop) const; // Retrieves the top of a stack. // Precondition: None. // Postcondition: If the stack is not empty, // stackTop contains the item that was added // most recently. However, if the stack is // empty, the operation fails and stackTop // is unchanged. The stack is unchanged.
  • 25. 19 July 2022 Anna University, Chennai - 600 025 25 Implementation Using Arrays
  • 26. 19 July 2022 Anna University, Chennai - 600 025 26 The Stack Class - Public Contents class Stack { public: Stack() { size = 10; current = -1;} int pop(){ return A[current--];} void push(int x){A[++current] = x;} int top(){ return A[current];} int isEmpty(){return ( current == -1 );} int isFull(){ return ( current == size-1);}
  • 27. 19 July 2022 Anna University, Chennai - 600 025 27 The Stack Class - Private Contents private: int object; // The data element int current; // Index of the array int size; // max size of the array int A[10]; // Array of 10 elements };
  • 28. 19 July 2022 Anna University, Chennai - 600 025 28 Stack - a Very Simple Application  The simplest application of a stack is to reverse a word.  You push a given word to stack - letter by letter - and then pop letters from the stack.
  • 29. 19 July 2022 Anna University, Chennai - 600 025 29 Applications of Stack  Recursion  Decimal to Binary Conversion  Infix to Postfix Conversion and Evaluation of Postfix Expressions  Rearranging Railroad Cars  Quick Sort  Function Calls  Undo button in various software.
  • 30. 19 July 2022 Anna University, Chennai - 600 025 30 outputInBinary - Algorithm function outputInBinary(Integer n) Stack s = new Stack while n > 0 do Integer bit = n modulo 2 s.push(bit) if s is full then return error end if n = floor(n / 2) end while while s is not empty do output(s.pop()) end while end function
  • 31. 19 July 2022 Anna University, Chennai - 600 025 31 Algebraic Expressions  Infix expressions • An operator appears between its operands  Example: a + b  Prefix expressions • An operator appears before its operands  Example: + a b  Postfix expressions • An operator appears after its operands  Example: a b +
  • 32. 19 July 2022 Anna University, Chennai - 600 025 32 A complicated example  Infix expressions: a + b * c + ( d * e + f ) * g  Postfix expressions: a b c * + d e * f + g * +  Prefix expressions: + + a * b c * + * d e f g
  • 33. 19 July 2022 Anna University, Chennai - 600 025 33 Evaluation of Postfix Expression
  • 34. 19 July 2022 Anna University, Chennai - 600 025 34 Evaluation of Postfix Expression  The calculation: 1 + 2 * 4 + 3 can be written down like this in postfix notation with the advantage of no precedence rules and parentheses needed  1 2 4 * + 3 +  The expression is evaluated from the left to right using a stack: • when encountering an operand: push it • when encountering an operator: pop two operands, evaluate the result and push it.
  • 35. 19 July 2022 Anna University, Chennai - 600 025 35
  • 36. 19 July 2022 Anna University, Chennai - 600 025 36 Infix to Postfix Conversion
  • 37. 19 July 2022 Anna University, Chennai - 600 025 37 What’s this ?
  • 38. 19 July 2022 Anna University, Chennai - 600 025 38 Queue
  • 39. 19 July 2022 Anna University, Chennai - 600 025 39 Queue  A stack is LIFO (Last-In First Out) structure. In contrast, a queue is a FIFO (First-In First- Out ) structure.  In a FIFO data structure, the first element added to the queue will be the first one to be removed.  A queue is a linear structure for which items can be only inserted at one end and removed at another end.
  • 40. 19 July 2022 Anna University, Chennai - 600 025 40 Operations on Queue  We will dedicate once again six operations on the Queue. • You can add a person to the queue (enque), • Look who is the first person to be serviced (front) • Rremove the first person (dequeue) and • Check whether the queue is empty (isEmpty). • Also there are two more operations to create and to destroy the queue.
  • 41. 19 July 2022 Anna University, Chennai - 600 025 41 Operations  Queue create() • Creates an empty queue  boolean isEmpty(Queue q) • Tells whether the queue q is empty  enqueue(Queue q, Item e) • Place e at the rear of the queue q  destroy(Queue q) • destroys queue q
  • 42. 19 July 2022 Anna University, Chennai - 600 025 42 Operations Continued  Item front(Queue q) • returns the front element in Queue q without removing it Precondition: q is not empty  dequeue(Queue q) • removes front element from the queue q Precondition: q is not empty
  • 43. 19 July 2022 Anna University, Chennai - 600 025 43 Implementation Using Arrays  If we use an array to hold queue elements, dequeue operation at the front (start) of the array is expensive.  This is because we may have to shift up to “n” elements.  For the stack, we needed only one end; for queue we need both.  To get around this, we will not shift upon removal of an element.
  • 44. 19 July 2022 Anna University, Chennai - 600 025 44 Snapshot of a Queue
  • 45. 19 July 2022 Anna University, Chennai - 600 025 45 enqueue()
  • 46. 19 July 2022 Anna University, Chennai - 600 025 46 enqueue() again
  • 47. 19 July 2022 Anna University, Chennai - 600 025 47 dequeue()
  • 48. 19 July 2022 Anna University, Chennai - 600 025 48 dequeue() again
  • 49. 19 July 2022 Anna University, Chennai - 600 025 49 Two more enqueue()
  • 50. 19 July 2022 Anna University, Chennai - 600 025 50 What’s Wrong ?  We have inserts and removal running in constant time but we created a new problem.  We cannot insert new elements even though there are two places available at the start of the array.  Solution: allow the queue to “wrap around”. Basic idea is to picture the array as a circular array as show below.
  • 51. 19 July 2022 Anna University, Chennai - 600 025 51 Queue array wrap-around
  • 52. 19 July 2022 Anna University, Chennai - 600 025 52 enqueue(element) void enqueue(int x) { rear = (rear+1)%size; array[rear] = x; noElements = noElements+1; }
  • 53. 19 July 2022 Anna University, Chennai - 600 025 53 dequeue() int dequeue() { int x = array[front]; front = (front+1)%size; noElements = noElements-1; return x; }
  • 54. 19 July 2022 Anna University, Chennai - 600 025 54 isEmpty() and isFull() int isFull() { return noElements == size; } int isEmpty() { return noElements == 0; }
  • 55. 19 July 2022 Anna University, Chennai - 600 025 55 Pointer Based Implementation  Possible implementations of a pointer-based queue • A linear linked list with two external references  A reference to the front  A reference to the back • A circular linked list with one external reference  A reference to the back
  • 56. 19 July 2022 Anna University, Chennai - 600 025 56 Queue - Linear and Circular List
  • 57. 19 July 2022 Anna University, Chennai - 600 025 57 Non-empty Queue - Insertion
  • 58. 19 July 2022 Anna University, Chennai - 600 025 58 Empty Queue - Insertion
  • 59. 19 July 2022 Anna University, Chennai - 600 025 59 Queue with more than 1 element - Deletion
  • 60. 19 July 2022 Anna University, Chennai - 600 025 60 Applications of Queues  Queue is used when things don’t have to be processed immediatly, but have to be processed in First In First Out order like Breadth First Search.  This property of Queue makes it also useful in following kind of scenarios.
  • 61. 19 July 2022 Anna University, Chennai - 600 025 61 Applications of Queues  When a resource is shared among multiple consumers. Examples include CPU scheduling, Disk Scheduling.  When data is transferred asynchronously (data not necessarily received at same rate as sent) between two processes. Examples include IO Buffers, pipes, file IO, etc.  Operating systems often maintain a queue of processes that are ready to execute or that are waiting for a particular event to occur.
  • 62. 19 July 2022 Anna University, Chennai - 600 025 62 Applications of Queues  Computer systems must often provide a “holding area” for messages between two processes, two programs, or even two systems. This holding area is usually called a “buffer” and is often implemented as a queue.  Call center phone systems will use a queue to hold people in line until a service representative is free.
  • 63. 19 July 2022 Anna University, Chennai - 600 025 63 Applications of Queues  Buffers on MP3 players and portable CD players, iPod playlist. Playlist for jukebox - add songs to the end, play from the front of the list.  Round Robin (RR) algorithm is an important scheduling algorithm. It is used especially for the time-sharing system. The circular queue is used to implement such algorithms.
  • 64. 19 July 2022 Anna University, Chennai - 600 025 64 Why Doubly Linked List ?  given only the pointer location, we cannot access its predecessor in the list.  Another task that is difficult to perform on a linear linked list is traversing the list in reverse.  Doubly linked list A linked list in which each node is linked to both its successor and its predecessor  In such a case, where we need to access the node that precedes a given node, a doubly linked list is useful.
  • 65. 19 July 2022 Anna University, Chennai - 600 025 65 Doubly Linked List  In a doubly linked list, the nodes are linked in both directions. Each node of a doubly linked list contains three parts: • Info: the data stored in the node • Next: the pointer to the following node • Back: the pointer to the preceding node
  • 66. 19 July 2022 Anna University, Chennai - 600 025 66 Operations on Doubly Linked Lists  The algorithms for the insertion and deletion operations on a doubly linked list are somewhat more complicated than the corresponding operations on a singly linked list.  The reason is clear: There are more pointers to keep track of in a doubly linked list.
  • 67. 19 July 2022 Anna University, Chennai - 600 025 67 Inserting Item  As an example, consider the Inserting an item.  To link the new node, after a given node, in a singly linked list, we need to change two pointers: • newNode->next and • location->next.  The same operation on a doubly linked list requires four pointer changes.
  • 68. 19 July 2022 Anna University, Chennai - 600 025 68 Singly Linked List Insertion
  • 69. 19 July 2022 Anna University, Chennai - 600 025 69 Doubly Linked List Insertion
  • 70. 19 July 2022 Anna University, Chennai - 600 025 70 The Order is Important
  • 71. 19 July 2022 Anna University, Chennai - 600 025 71 Doubly Linked List - Deletion  One useful feature of a doubly linked list is its elimination of the need for a pointer to a node's predecessor to delete the node.  Through the back member, we can alter the next member of the preceding node to make it jump over the unwanted node.  Then we make the back pointer of the succeeding node point to the preceding node.
  • 72. 19 July 2022 Anna University, Chennai - 600 025 72 Doubly Linked List - Deletion
  • 73. 19 July 2022 Anna University, Chennai - 600 025 73 Special Cases of Deletion  We do, however, have to be careful about the end cases: • If location->back is NULL, we are deleting the first node • if location->next is NULL, we are deleting the last node. • If both location->back and location->next are NULL, we are deleting the only node.
  • 74. 19 July 2022 Anna University, Chennai - 600 025 74 Interaction