SlideShare a Scribd company logo
1 of 64
CS201: Data Structures and
Discrete Mathematics I
Linked Lists, Stacks and Queues
5/7/2023 CS 201
Data Structure
• A construct that can be defined within a
programming language to store a
collection of data
– one may store some data in an array of
integers, an array of objects, or an array of
arrays
5/7/2023 CS 201
Abstract Data Type (ADT)
• Definition: a collection of data together
with a set of operations on that data
– specifications indicate what ADT
operations do, but not how to implement
them
– data structures are part of an ADT’s
implementation
• Programmer can use an ADT without
knowing its implementation.
5/7/2023 CS 201
Typical Operations on Data
• Add data to a data collection
• Remove data from a data collection
• Ask questions about the data in a data
collection. E.g., what is the value at a
particular location, and is x in the
collection?
5/7/2023 CS 201
Why ADT
• Hide the unnecessary details
• Help manage software complexity
• Easier software maintenance
• Functionalities are less likely to change
• Localised rather than global changes
5/7/2023 CS 201
Illustration
Linked Lists
5/7/2023 CS 201
Lists
• List: a finite sequence of data items
a1, a2, a3, …, an
• Lists are pervasive in computing
– e.g. class list, list of chars, list of events
• Typical operations:
– Creation
– Insert / remove an element
– Test for emptiness
– Find an item/element
– Current element / next / previous
– Find k-th element
– Print the entire list
5/7/2023 CS 201
Array-Based List Implementation
• One simple implementation is to use arrays
– A sequence of n-elements
• Maximum size is anticipated a priori.
• Internal variables:
– Maximum size maxSize (m)
– Current size curSize (n)
– Current index cur
– Array of elements listArray
n
curSize
a1 a2 a3 an
listArray
unused
0 1 2 n-1 m
cur
5/7/2023 CS 201
Inserting Into an Array
• While retrieval is very fast, insertion and
deletion are very slow
– Insert has to shift upwards to create gap
a1 a2 a7 a8
a4 a5 a6
a3
Step 1 : Shift upwards
8
Size arr
8 a1 a2 a3 a7 a8
Size arr
a4 a5 a6
Example : insert(2, it, arr)
Step 2 : Write into gap
it
Step 3 : Update Size
9
5/7/2023 CS 201
Coding
typedef struct {
int arr[MAX];
int max;
int size;
} LIST
void insert(int j, int it, LIST *pl)
{ // pre : 1<=j<=size+1
int i;
for (i=pl->size; i>=j; i=i-1)
// Step 1: Create gap
{ pl->arr[i+1]= pl->arr[i]; };
pl->arr[j]= it; // Step 2: Write to gap
pl->size = pl->size + 1; // Step 3: Update size
}
5/7/2023 CS 201
Deleting from an Array
• Delete has to shift downwards to close gap of
deleted item
Step 1 : Close Gap
9 a1 a2 it a7
a8
size
a5 a6
a3
a8
arr
9 a1 a2 it a7 a8
size
a4 a5 a6
a3
arr
Example: deleteItem(4, arr)
Step 2 : Update Size
8
Not part of list
5/7/2023 CS 201
Coding
void delete(int j, LIST *pl)
{ // pre : 1<=j<=size
for (i=j+1; i<=pl->size; i=i+1)
// Step1: Close gap
{ pl->arr[i-i]=pl->arr[i]; };
// Step 2: Update size
pl->size = pl->size - 1;
}
5/7/2023 CS 201
Linked List Approach
• Main problem of array is the slow deletion/insertion since it
has to shift items in its contiguous memory
• Solution: linked list where items need not be contiguous
with nodes of the form
• Sequence (list) of four items < a1,a2 ,a3 ,a4 > can be
represented by:
item next
ai
a1 a2 a3 a4
head represents
null
Pointer-Based Linked Lists
• A node in a linked list is usually a struct
struct Node
{ int item
Node *next;
}; //end struct
• A node is dynamically allocated
Node *p;
p = malloc(sizeof(Node));
A node
5/7/2023 CS 201
Pointer-Based Linked Lists
• The head pointer points to the first node
in a linked list
• If head is NULL, the linked list is empty
– head=NULL
• head=malloc(sizeof(Node))
5/7/2023 CS 201
A Sample Linked List
5/7/2023 CS 201
Traverse a Linked List
• Reference a node member with the ->
operator
p->item;
• A traverse operation visits each node in
the linked list
– A pointer variable cur keeps track of the
current node
for (Node *cur = head;
cur != NULL; cur = cur->next)
x = cur->item;
5/7/2023 CS 201
Traverse a Linked List
The effect of the assignment cur = cur->next
5/7/2023 CS 201
Delete a Node from a Linked List
• Deleting an interior/last node
prev->next=cur->next;
• Deleting the first node
head=head->next;
• Return deleted node to system
cur->next = NULL;
free(cur);
cur=NULL;
5/7/2023 CS 201
Delete a Node from a Linked List
Deleting a node from a linked list
Deleting the first node
5/7/2023 CS 201
Insert a Node into a Linked List
• To insert a node between two nodes
newPtr->next = cur;
prev->next = newPtr;
Inserting a new node
into a linked list
CS 201
Insert a Node into a Linked List
• To insert a node at the beginning of a
linked list
newPtr->next = head;
head = newPtr;
Inserting at the beginning
of a linked list
CS 201
Insert a Node into a Linked List
• Inserting at the end of a linked list is not
a special case if cur is NULL
newPtr->next = cur;
prev->next = newPtr;
Inserting at the end of a
linked list
CS 201
Look up
BOOLEAN lookup (int x, Node *L)
{ if (L == NULL)
return FALSE
else if (x == L->item)
return TRUE
else
return lookup(x, L-next);
}
5/7/2023 CS 201
An ADT Interface for List
• Functions
– isEmpty
– getLength
– insert
– delete
– Lookup
– …
• Data Members
– head
– Size
• Local variables to
member functions
– cur
– prev
5/7/2023 CS 201
5/7/2023 CS 201
Doubly Liked Lists
• Frequently, we need to traverse a sequence
in BOTH directions efficiently
• Solution : Use doubly-linked list where each
node has two pointers
next
forward traversal
Doubly Linked List.
x1 x4
x2
head
x3
backward traversal
prev
5/7/2023 CS 201
Circular Linked Lists
• May need to cycle through a list repeatedly,
e.g. round robin system for a shared resource
• Solution : Have the last node point to the first
node
x1 x2 xn
. . .
Circular Linked List.
head
Stacks
5/7/2023 CS 201
What is a Stack?
• A stack is a list with the restriction that
insertions and deletions can be performed in
only one position, namely, the end of the list,
called the top.
• The operations: push (insert) and pop (delete)
pop push(o)
6
7
2
3
Top
5/7/2023 CS 201
Stack ADT Interface
• The main functions in the Stack ADT are (S is the stack)
boolean isEmpty(); // return true if empty
boolean isFull(S); // return true if full
void push(S, item); // insert item into stack
void pop(S); // remove most recent item
void clear(S); // remove all items from stack
Item top(S); // retrieve most recent item
Item topAndPop(S); // return & remove most recent item
5/7/2023 CS 201
Sample Operation
Stack S = malloc(sizeof(stack));
push(S, “a”);
push(S, “b”);
push(S, “c”);
d=top(S);
pop(S);
push(S, “e”);
pop(S);
s
a
b
c
top
d
5/7/2023 CS 201
Implementation by Linked Lists
• Can use a Linked List as implementation of stack
Top of Stack = Front of Linked-List
StackLL
lst
a1 a2 a3 a4
head
LinkedListItr
5/7/2023 CS 201
Code
struct Node {
int element;
Node * next;
};
typedef struct Node * STACK;
5/7/2023 CS 201
More code
More Code
5/7/2023 CS 201
5/7/2023 CS 201
Implementation by Array
• use Array with a top index pointer as an implementation of stack
E F
0 1 7 8 9
2 3 4 5 6
A B C D
top
StackAr
arr
A
5/7/2023 CS 201
Code
5/7/2023 CS 201
More code
5/7/2023 CS 201
More code
Effects
5/7/2023 CS 201
5/7/2023 CS 201
Applications
• Many application areas use stacks:
– line editing
– bracket matching
– postfix calculation
– function call stack
5/7/2023 CS 201
Line Editing
• A line editor would place characters read into a
buffer but may use a backspace symbol (denoted by
) to do error correction
• Refined Task
– read in a line
– correct the errors via backspace
– print the corrected line in reverse
Input :
Corrected Input :
Reversed Output :
abc_defgh2klpqrwxyz
abc_defg2klpwxyz
zyxwplk2gfed_cba
5/7/2023 CS 201
The Procedure
• Initialize a new stack
• For each character read:
– if it is a backspace, pop out last char
entered
– if not a backspace, push the char into
stack
• To print in reverse, pop out each char for
output
Input : fghryz
Corrected Input :
Reversed Output :
fyz
zyf Stack
f
g
h
r
y
z
5/7/2023 CS 201
Bracket Matching Problem
• Ensures that pairs of brackets are properly matched
• An Example: {a,(b+f[4])*3,d+f[5]}
• Bad Examples:
(..)..) // too many closing brackets
(..(..) // too many open brackets
[..(..]..) // mismatched brackets
5/7/2023 CS 201
Informal Procedure
Initialize the stack to empty
For every char read
if open bracket then push onto stack
if close bracket, then
return & remove most recent item
from the stack
if doesn’t match then flag error
if non-bracket, skip the char read
Example
{a,(b+f[4])*3,d+f[5]}
Stack
{
(
[
)
}
]
[ ]
5/7/2023 CS 201
Postfix Calculator
• Computation of arithmetic expressions can be efficiently
carried out in Postfix notation with the help of a stack.
Infix - arg1 op arg2
Prefix - op arg1 arg2
Postfix - arg1 arg2 op
(2*3)+4
2*(3+4) 2 3 4 + *
2*3+4
infix
2 3 * 4 +
postfix
5/7/2023 CS 201
Informal Procedure
Initialise stack S
For each item read.
If it is an operand,
push on the stack
If it is an operator,
pop arguments from stack;
perform operation;
push result onto the stack
2
3
4
Stack
Expr
2
3
4
+
*
push(S, 2)
push(S, 3)
push(S, 4)
arg2=topAndPop(S)
arg1=topAndPop(S)
push(S, arg1+arg2)
arg2=topAndPop(S)
arg1=topAndPop(S)
push(S, arg1*arg2)
3+4=7
2*7=14
5/7/2023 CS 201
Summary
• The ADT stack operations have a last-
in, first-out (LIFO) behavior
• Stack has many applications
– algorithms that operate on algebraic
expressions
– a strong relationship between recursion
and stacks exists
• Stack can be implemented using arrays
or linked lists
Queues
5/7/2023 CS 201
What is a Queue?
• Like stacks, queues are lists. With a queue,
however, insertion is done at one end whereas
deletion is done at the other end.
• Queues implement the FIFO (first-in first-out)
policy. E.g., a printer/job queue!
• Two basic operations of queues:
– dequeue: remove an item/element from front
– enqueue: add an item/element at the back
dequeue enqueue
5/7/2023 CS 201
Queue ADT
• Queues implement the FIFO (first-in first-out)
policy
– An example is the printer/job queue!
enqueue(o)
dequeue()
isEmpty()
getFront() createQueue()
5/7/2023 CS 201
Sample Operation
Queue *Q;
enqueue(Q, “a”);
enqueue(Q, “b”);
enqueue(Q, “c”);
d=getFront(Q);
dequeue(Q);
enqueue(Q, “e”);
dequeue(Q);
q
front back
a b c e
d
5/7/2023 CS 201
Queue ADT interface
• The main functions in the Queue ADT are (Q is
the queue)
void enqueue(o, Q) // insert o to back of Q
void dequeue(Q); // remove oldest item
Item getFront(Q); // retrieve oldest item
boolean isEmpty(Q); // checks if Q is empty
boolean isFull(Q); // checks if Q is full
void clear(Q); // make Q empty
}
5/7/2023 CS 201
Implementation of Queue
(Linked List)
• Can use LinkedListItr as underlying implementation of Queues
a1 a2 a3 a4
head tail
Queue
lst
LinkedList
addTail
5/7/2023 CS 201
Code
struct Node {
int element;
Node * next;
};
struct QUEUE {
Node * front;
Node * rear;
};
5/7/2023 CS 201
More code
More code
5/7/2023 CS 201
CELL is a list node
5/7/2023 CS 201
Implementation of Queue
(Array)
• use Array with front and back pointers as implementation of
queue Queue
arr 0 1 7 8 9
2 3 4 5 6
A B C D E F G
front
back
5/7/2023 CS 201
Circular Array
• To implement queue, it is best to view arrays as circular structure
0 1 7 8 9
2 3 4 5 6
A B C D E F G
front
back
front
back
A
B
C
D
E
F
G
0
1
7
8
9
2
3
4
5
6
Circular view of arrays.
5/7/2023 CS 201
How to Advance
• Both front & back pointers should make advancement until they
reach end of the array. Then, they should re-point to beginning
of the array
front = adv(front);
back = adv(back);
int adv(int p)
{ return ((p+1) % maxsize);
}
Alternatively, use modular arithmetic:
mod operator
int adv(int p)
{ int r = p+1;
if (r<maxsize) return r;
else return 0;
}
upper bound of the array
5/7/2023 CS 201
Sample
Queue *Q;
enqueue(Q, “a”);
enqueue(Q, “b”);
enqueue(Q, “c”);
dequeue(Q);
dequeue(Q);
enqueue(Q, “d”);
enqueue(Q, “e”);
dequeue(Q);
a
Q
F=front
B=back
F
B
b c d
F
B B B
F F
B B
e
5/7/2023 CS 201
Checking for Full/Empty State
What does (F==B) denote?
F
B
Queue
Empty
State
c d
e
B
F
f Queue
Full
State
size 0 size 4
c d
e
B F
Alternative - Leave a Deliberate Gap!
No need for size field.
Full Case : (adv(B)==F)
5/7/2023 CS 201
Summary
• The definition of the queue operations
gives the ADT queue first-in, first-out
(FIFO) behavior
• The queue can be implemented by
linked lists or by arrays
• There are many applications
– Printer queues,
– Telecommunication queues,
– Simulations,
– Etc.

More Related Content

Similar to lect- 3&4.ppt

Similar to lect- 3&4.ppt (20)

Linked list1.ppt
Linked list1.pptLinked list1.ppt
Linked list1.ppt
 
Linked List.ppt
Linked List.pptLinked List.ppt
Linked List.ppt
 
Wk11-linkedlist.ppt
Wk11-linkedlist.pptWk11-linkedlist.ppt
Wk11-linkedlist.ppt
 
Wk11-linkedlist.ppt
Wk11-linkedlist.pptWk11-linkedlist.ppt
Wk11-linkedlist.ppt
 
Wk11-linkedlist.ppt
Wk11-linkedlist.pptWk11-linkedlist.ppt
Wk11-linkedlist.ppt
 
Data structures
Data structuresData structures
Data structures
 
linked list
linked listlinked list
linked list
 
Python - Lecture 12
Python - Lecture 12Python - Lecture 12
Python - Lecture 12
 
STACK1.pptx
STACK1.pptxSTACK1.pptx
STACK1.pptx
 
Stack in Sata Structure
Stack in Sata StructureStack in Sata Structure
Stack in Sata Structure
 
Algorithms devised for a google interview
Algorithms devised for a google interviewAlgorithms devised for a google interview
Algorithms devised for a google interview
 
Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
 
Wk11-linkedlist.ppt
Wk11-linkedlist.pptWk11-linkedlist.ppt
Wk11-linkedlist.ppt
 
Wk11-linkedlist.ppt
Wk11-linkedlist.pptWk11-linkedlist.ppt
Wk11-linkedlist.ppt
 
II B.Sc IT DATA STRUCTURES.pptx
II B.Sc IT DATA STRUCTURES.pptxII B.Sc IT DATA STRUCTURES.pptx
II B.Sc IT DATA STRUCTURES.pptx
 
2 a stacks
2 a stacks2 a stacks
2 a stacks
 
Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9
 
Rana Junaid Rasheed
Rana Junaid RasheedRana Junaid Rasheed
Rana Junaid Rasheed
 
Ch03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptCh03_stacks_and_queues.ppt
Ch03_stacks_and_queues.ppt
 
Data structure
 Data structure Data structure
Data structure
 

Recently uploaded

NLP Data Science Project Presentation:Predicting Heart Disease with NLP Data ...
NLP Data Science Project Presentation:Predicting Heart Disease with NLP Data ...NLP Data Science Project Presentation:Predicting Heart Disease with NLP Data ...
NLP Data Science Project Presentation:Predicting Heart Disease with NLP Data ...Boston Institute of Analytics
 
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)jennyeacort
 
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024thyngster
 
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...soniya singh
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfSocial Samosa
 
ASML's Taxonomy Adventure by Daniel Canter
ASML's Taxonomy Adventure by Daniel CanterASML's Taxonomy Adventure by Daniel Canter
ASML's Taxonomy Adventure by Daniel Cantervoginip
 
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一fhwihughh
 
RABBIT: A CLI tool for identifying bots based on their GitHub events.
RABBIT: A CLI tool for identifying bots based on their GitHub events.RABBIT: A CLI tool for identifying bots based on their GitHub events.
RABBIT: A CLI tool for identifying bots based on their GitHub events.natarajan8993
 
Call Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts ServiceCall Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts ServiceSapana Sha
 
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptdokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptSonatrach
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptxthyngster
 
INTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTDINTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTDRafezzaman
 
办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree
办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree
办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degreeyuu sss
 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfLars Albertsson
 
GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]📊 Markus Baersch
 
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样vhwb25kk
 
Customer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptxCustomer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptxEmmanuel Dauda
 
Top 5 Best Data Analytics Courses In Queens
Top 5 Best Data Analytics Courses In QueensTop 5 Best Data Analytics Courses In Queens
Top 5 Best Data Analytics Courses In Queensdataanalyticsqueen03
 

Recently uploaded (20)

NLP Data Science Project Presentation:Predicting Heart Disease with NLP Data ...
NLP Data Science Project Presentation:Predicting Heart Disease with NLP Data ...NLP Data Science Project Presentation:Predicting Heart Disease with NLP Data ...
NLP Data Science Project Presentation:Predicting Heart Disease with NLP Data ...
 
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
 
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
Consent & Privacy Signals on Google *Pixels* - MeasureCamp Amsterdam 2024
 
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
 
ASML's Taxonomy Adventure by Daniel Canter
ASML's Taxonomy Adventure by Daniel CanterASML's Taxonomy Adventure by Daniel Canter
ASML's Taxonomy Adventure by Daniel Canter
 
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
 
RABBIT: A CLI tool for identifying bots based on their GitHub events.
RABBIT: A CLI tool for identifying bots based on their GitHub events.RABBIT: A CLI tool for identifying bots based on their GitHub events.
RABBIT: A CLI tool for identifying bots based on their GitHub events.
 
Call Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts ServiceCall Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts Service
 
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptdokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
 
INTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTDINTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTD
 
办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree
办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree
办美国阿肯色大学小石城分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree
 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdf
 
GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]
 
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
 
Deep Generative Learning for All - The Gen AI Hype (Spring 2024)
Deep Generative Learning for All - The Gen AI Hype (Spring 2024)Deep Generative Learning for All - The Gen AI Hype (Spring 2024)
Deep Generative Learning for All - The Gen AI Hype (Spring 2024)
 
Call Girls in Saket 99530🔝 56974 Escort Service
Call Girls in Saket 99530🔝 56974 Escort ServiceCall Girls in Saket 99530🔝 56974 Escort Service
Call Girls in Saket 99530🔝 56974 Escort Service
 
Customer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptxCustomer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptx
 
Top 5 Best Data Analytics Courses In Queens
Top 5 Best Data Analytics Courses In QueensTop 5 Best Data Analytics Courses In Queens
Top 5 Best Data Analytics Courses In Queens
 

lect- 3&4.ppt

  • 1. CS201: Data Structures and Discrete Mathematics I Linked Lists, Stacks and Queues
  • 2. 5/7/2023 CS 201 Data Structure • A construct that can be defined within a programming language to store a collection of data – one may store some data in an array of integers, an array of objects, or an array of arrays
  • 3. 5/7/2023 CS 201 Abstract Data Type (ADT) • Definition: a collection of data together with a set of operations on that data – specifications indicate what ADT operations do, but not how to implement them – data structures are part of an ADT’s implementation • Programmer can use an ADT without knowing its implementation.
  • 4. 5/7/2023 CS 201 Typical Operations on Data • Add data to a data collection • Remove data from a data collection • Ask questions about the data in a data collection. E.g., what is the value at a particular location, and is x in the collection?
  • 5. 5/7/2023 CS 201 Why ADT • Hide the unnecessary details • Help manage software complexity • Easier software maintenance • Functionalities are less likely to change • Localised rather than global changes
  • 8. 5/7/2023 CS 201 Lists • List: a finite sequence of data items a1, a2, a3, …, an • Lists are pervasive in computing – e.g. class list, list of chars, list of events • Typical operations: – Creation – Insert / remove an element – Test for emptiness – Find an item/element – Current element / next / previous – Find k-th element – Print the entire list
  • 9. 5/7/2023 CS 201 Array-Based List Implementation • One simple implementation is to use arrays – A sequence of n-elements • Maximum size is anticipated a priori. • Internal variables: – Maximum size maxSize (m) – Current size curSize (n) – Current index cur – Array of elements listArray n curSize a1 a2 a3 an listArray unused 0 1 2 n-1 m cur
  • 10. 5/7/2023 CS 201 Inserting Into an Array • While retrieval is very fast, insertion and deletion are very slow – Insert has to shift upwards to create gap a1 a2 a7 a8 a4 a5 a6 a3 Step 1 : Shift upwards 8 Size arr 8 a1 a2 a3 a7 a8 Size arr a4 a5 a6 Example : insert(2, it, arr) Step 2 : Write into gap it Step 3 : Update Size 9
  • 11. 5/7/2023 CS 201 Coding typedef struct { int arr[MAX]; int max; int size; } LIST void insert(int j, int it, LIST *pl) { // pre : 1<=j<=size+1 int i; for (i=pl->size; i>=j; i=i-1) // Step 1: Create gap { pl->arr[i+1]= pl->arr[i]; }; pl->arr[j]= it; // Step 2: Write to gap pl->size = pl->size + 1; // Step 3: Update size }
  • 12. 5/7/2023 CS 201 Deleting from an Array • Delete has to shift downwards to close gap of deleted item Step 1 : Close Gap 9 a1 a2 it a7 a8 size a5 a6 a3 a8 arr 9 a1 a2 it a7 a8 size a4 a5 a6 a3 arr Example: deleteItem(4, arr) Step 2 : Update Size 8 Not part of list
  • 13. 5/7/2023 CS 201 Coding void delete(int j, LIST *pl) { // pre : 1<=j<=size for (i=j+1; i<=pl->size; i=i+1) // Step1: Close gap { pl->arr[i-i]=pl->arr[i]; }; // Step 2: Update size pl->size = pl->size - 1; }
  • 14. 5/7/2023 CS 201 Linked List Approach • Main problem of array is the slow deletion/insertion since it has to shift items in its contiguous memory • Solution: linked list where items need not be contiguous with nodes of the form • Sequence (list) of four items < a1,a2 ,a3 ,a4 > can be represented by: item next ai a1 a2 a3 a4 head represents null
  • 15. Pointer-Based Linked Lists • A node in a linked list is usually a struct struct Node { int item Node *next; }; //end struct • A node is dynamically allocated Node *p; p = malloc(sizeof(Node)); A node 5/7/2023 CS 201
  • 16. Pointer-Based Linked Lists • The head pointer points to the first node in a linked list • If head is NULL, the linked list is empty – head=NULL • head=malloc(sizeof(Node)) 5/7/2023 CS 201
  • 17. A Sample Linked List 5/7/2023 CS 201
  • 18. Traverse a Linked List • Reference a node member with the -> operator p->item; • A traverse operation visits each node in the linked list – A pointer variable cur keeps track of the current node for (Node *cur = head; cur != NULL; cur = cur->next) x = cur->item; 5/7/2023 CS 201
  • 19. Traverse a Linked List The effect of the assignment cur = cur->next 5/7/2023 CS 201
  • 20. Delete a Node from a Linked List • Deleting an interior/last node prev->next=cur->next; • Deleting the first node head=head->next; • Return deleted node to system cur->next = NULL; free(cur); cur=NULL; 5/7/2023 CS 201
  • 21. Delete a Node from a Linked List Deleting a node from a linked list Deleting the first node 5/7/2023 CS 201
  • 22. Insert a Node into a Linked List • To insert a node between two nodes newPtr->next = cur; prev->next = newPtr; Inserting a new node into a linked list CS 201
  • 23. Insert a Node into a Linked List • To insert a node at the beginning of a linked list newPtr->next = head; head = newPtr; Inserting at the beginning of a linked list CS 201
  • 24. Insert a Node into a Linked List • Inserting at the end of a linked list is not a special case if cur is NULL newPtr->next = cur; prev->next = newPtr; Inserting at the end of a linked list CS 201
  • 25. Look up BOOLEAN lookup (int x, Node *L) { if (L == NULL) return FALSE else if (x == L->item) return TRUE else return lookup(x, L-next); } 5/7/2023 CS 201
  • 26. An ADT Interface for List • Functions – isEmpty – getLength – insert – delete – Lookup – … • Data Members – head – Size • Local variables to member functions – cur – prev 5/7/2023 CS 201
  • 27. 5/7/2023 CS 201 Doubly Liked Lists • Frequently, we need to traverse a sequence in BOTH directions efficiently • Solution : Use doubly-linked list where each node has two pointers next forward traversal Doubly Linked List. x1 x4 x2 head x3 backward traversal prev
  • 28. 5/7/2023 CS 201 Circular Linked Lists • May need to cycle through a list repeatedly, e.g. round robin system for a shared resource • Solution : Have the last node point to the first node x1 x2 xn . . . Circular Linked List. head
  • 30. 5/7/2023 CS 201 What is a Stack? • A stack is a list with the restriction that insertions and deletions can be performed in only one position, namely, the end of the list, called the top. • The operations: push (insert) and pop (delete) pop push(o) 6 7 2 3 Top
  • 31. 5/7/2023 CS 201 Stack ADT Interface • The main functions in the Stack ADT are (S is the stack) boolean isEmpty(); // return true if empty boolean isFull(S); // return true if full void push(S, item); // insert item into stack void pop(S); // remove most recent item void clear(S); // remove all items from stack Item top(S); // retrieve most recent item Item topAndPop(S); // return & remove most recent item
  • 32. 5/7/2023 CS 201 Sample Operation Stack S = malloc(sizeof(stack)); push(S, “a”); push(S, “b”); push(S, “c”); d=top(S); pop(S); push(S, “e”); pop(S); s a b c top d
  • 33. 5/7/2023 CS 201 Implementation by Linked Lists • Can use a Linked List as implementation of stack Top of Stack = Front of Linked-List StackLL lst a1 a2 a3 a4 head LinkedListItr
  • 34. 5/7/2023 CS 201 Code struct Node { int element; Node * next; }; typedef struct Node * STACK;
  • 37. 5/7/2023 CS 201 Implementation by Array • use Array with a top index pointer as an implementation of stack E F 0 1 7 8 9 2 3 4 5 6 A B C D top StackAr arr A
  • 42. 5/7/2023 CS 201 Applications • Many application areas use stacks: – line editing – bracket matching – postfix calculation – function call stack
  • 43. 5/7/2023 CS 201 Line Editing • A line editor would place characters read into a buffer but may use a backspace symbol (denoted by ) to do error correction • Refined Task – read in a line – correct the errors via backspace – print the corrected line in reverse Input : Corrected Input : Reversed Output : abc_defgh2klpqrwxyz abc_defg2klpwxyz zyxwplk2gfed_cba
  • 44. 5/7/2023 CS 201 The Procedure • Initialize a new stack • For each character read: – if it is a backspace, pop out last char entered – if not a backspace, push the char into stack • To print in reverse, pop out each char for output Input : fghryz Corrected Input : Reversed Output : fyz zyf Stack f g h r y z
  • 45. 5/7/2023 CS 201 Bracket Matching Problem • Ensures that pairs of brackets are properly matched • An Example: {a,(b+f[4])*3,d+f[5]} • Bad Examples: (..)..) // too many closing brackets (..(..) // too many open brackets [..(..]..) // mismatched brackets
  • 46. 5/7/2023 CS 201 Informal Procedure Initialize the stack to empty For every char read if open bracket then push onto stack if close bracket, then return & remove most recent item from the stack if doesn’t match then flag error if non-bracket, skip the char read Example {a,(b+f[4])*3,d+f[5]} Stack { ( [ ) } ] [ ]
  • 47. 5/7/2023 CS 201 Postfix Calculator • Computation of arithmetic expressions can be efficiently carried out in Postfix notation with the help of a stack. Infix - arg1 op arg2 Prefix - op arg1 arg2 Postfix - arg1 arg2 op (2*3)+4 2*(3+4) 2 3 4 + * 2*3+4 infix 2 3 * 4 + postfix
  • 48. 5/7/2023 CS 201 Informal Procedure Initialise stack S For each item read. If it is an operand, push on the stack If it is an operator, pop arguments from stack; perform operation; push result onto the stack 2 3 4 Stack Expr 2 3 4 + * push(S, 2) push(S, 3) push(S, 4) arg2=topAndPop(S) arg1=topAndPop(S) push(S, arg1+arg2) arg2=topAndPop(S) arg1=topAndPop(S) push(S, arg1*arg2) 3+4=7 2*7=14
  • 49. 5/7/2023 CS 201 Summary • The ADT stack operations have a last- in, first-out (LIFO) behavior • Stack has many applications – algorithms that operate on algebraic expressions – a strong relationship between recursion and stacks exists • Stack can be implemented using arrays or linked lists
  • 51. 5/7/2023 CS 201 What is a Queue? • Like stacks, queues are lists. With a queue, however, insertion is done at one end whereas deletion is done at the other end. • Queues implement the FIFO (first-in first-out) policy. E.g., a printer/job queue! • Two basic operations of queues: – dequeue: remove an item/element from front – enqueue: add an item/element at the back dequeue enqueue
  • 52. 5/7/2023 CS 201 Queue ADT • Queues implement the FIFO (first-in first-out) policy – An example is the printer/job queue! enqueue(o) dequeue() isEmpty() getFront() createQueue()
  • 53. 5/7/2023 CS 201 Sample Operation Queue *Q; enqueue(Q, “a”); enqueue(Q, “b”); enqueue(Q, “c”); d=getFront(Q); dequeue(Q); enqueue(Q, “e”); dequeue(Q); q front back a b c e d
  • 54. 5/7/2023 CS 201 Queue ADT interface • The main functions in the Queue ADT are (Q is the queue) void enqueue(o, Q) // insert o to back of Q void dequeue(Q); // remove oldest item Item getFront(Q); // retrieve oldest item boolean isEmpty(Q); // checks if Q is empty boolean isFull(Q); // checks if Q is full void clear(Q); // make Q empty }
  • 55. 5/7/2023 CS 201 Implementation of Queue (Linked List) • Can use LinkedListItr as underlying implementation of Queues a1 a2 a3 a4 head tail Queue lst LinkedList addTail
  • 56. 5/7/2023 CS 201 Code struct Node { int element; Node * next; }; struct QUEUE { Node * front; Node * rear; };
  • 58. More code 5/7/2023 CS 201 CELL is a list node
  • 59. 5/7/2023 CS 201 Implementation of Queue (Array) • use Array with front and back pointers as implementation of queue Queue arr 0 1 7 8 9 2 3 4 5 6 A B C D E F G front back
  • 60. 5/7/2023 CS 201 Circular Array • To implement queue, it is best to view arrays as circular structure 0 1 7 8 9 2 3 4 5 6 A B C D E F G front back front back A B C D E F G 0 1 7 8 9 2 3 4 5 6 Circular view of arrays.
  • 61. 5/7/2023 CS 201 How to Advance • Both front & back pointers should make advancement until they reach end of the array. Then, they should re-point to beginning of the array front = adv(front); back = adv(back); int adv(int p) { return ((p+1) % maxsize); } Alternatively, use modular arithmetic: mod operator int adv(int p) { int r = p+1; if (r<maxsize) return r; else return 0; } upper bound of the array
  • 62. 5/7/2023 CS 201 Sample Queue *Q; enqueue(Q, “a”); enqueue(Q, “b”); enqueue(Q, “c”); dequeue(Q); dequeue(Q); enqueue(Q, “d”); enqueue(Q, “e”); dequeue(Q); a Q F=front B=back F B b c d F B B B F F B B e
  • 63. 5/7/2023 CS 201 Checking for Full/Empty State What does (F==B) denote? F B Queue Empty State c d e B F f Queue Full State size 0 size 4 c d e B F Alternative - Leave a Deliberate Gap! No need for size field. Full Case : (adv(B)==F)
  • 64. 5/7/2023 CS 201 Summary • The definition of the queue operations gives the ADT queue first-in, first-out (FIFO) behavior • The queue can be implemented by linked lists or by arrays • There are many applications – Printer queues, – Telecommunication queues, – Simulations, – Etc.