Chapter Three-Linear Data Structure
1
Daata Structure &
Algorithm
Part 1-LINKED LISTS
o A linked list is a linear data structure, in which the
elements are not stored at contiguous memory
locations.
o The elements in a linked list are linked using pointers
o It is self-referential structure.
o It is a collection of elements called nodes,
 A node stores two types of fields:
o Data items and a pointer/link .
2
Daata Structure & Algorithm
Introduction
o The data field holds the actual elements on the list
o The pointer field contains the address of the next
node in the list- Singly linked list
o The pointer field contains the address of the
previous node in the list - doubly linked list
Cont
’
3
Daata Structure & Algorithm
o Let’s Store 12, 34, 40 and 56 using linked list
o First Create four different nodes then create link
How to access the first element?
Cont
’
100 300 400
12 300 34 400 40 500 56 NULL
500
100 head
4
Daata Structure & Algorithm
o In linked list, flexible space use by dynamically
allocating space for each element as needed.
o Successive elements are connected by
pointers and last element points to NULL.
o This implies that one need not know the size of the
list in advance.
Can change memory during execution.
 So, memory is efficiently utilized compared to array.
5
Daata Structure & Algorithm
Cont
’
• The figure below shows a linked list called scores
that contains four elements.
• And also shows an example of an empty linked
list.
6
Daata Structure &
Algorithm
Array Vs Linked
List
 Both an array and a linked list are representations of a list of
items in memory. The only difference is the way in which the
items are linked together.
Array:
 Sequential mapping
 Elements are fixed distance apart.
 Makes insertion or deletion at any arbitrary position in an
array a costly operation.
 Randomly accessing any element…. Etc.
7
Daata Structure & Algorithm
Linked List:
Not necessary that the elements be at a fixed
distance apart
An element is required to be linked with a previous
element of the list
Suitable for Inserting/deleting an element.
Done by storing the address of the next element
8
Daata Structure & Algorithm
Cont
’
Cont
’
9
Daata Structure &
Algorithm
Cont
’
 Like array a linked list must have a name.
 The name of a linked list is the name of the head pointer
that points to the first node of the list.
10
Daata Structure & Algorithm
Linked list operations
The following are the basic operations supported by a
list.
⚫Display − Displays the complete list.
⚫Search − Searches an element using the given key.
⚫Insertion − Adds an element at the beginning of
the list.
⚫Deletion − Deletes an element at the beginning of
the list. Deletes an element using the given key.
Daata Structure & Algorithm 11
Revision on Pointers
Data structures&Algorithms
12
⚫A pointer is a variable that points to another
variable.
⚫This means that a pointer holds the memory address
of another variable.
⚫ The pointer does not hold a value in the
traditional sense; instead, it holds the address of
another variable.
⚫A pointer "points to" that other variable by holding a
copy of its address.
Daata Structure & Algorithm 12
Display the content of list
Steps:
⚫ Set a temporary pointer to point to the same thing as the start
pointer.
⚫ If the pointer points to NULL, display the message "End of list" and
stop.
⚫ Otherwise, display the data values of the node pointed to by the start
pointer.
⚫ Make the temporary pointer point to the same thing as the next
pointer of the node it is currently indicating.
⚫ Jump back to step 2.
Daata Structure & Algorithm 13
Searching operation on Linked List
14
Daata Structure & Algorithm
 Since nodes in a linked list have no names, we use
two pointers, pre (for previous) and cur (for
current).
 At the beginning of the search, the pre pointer is
null and the cur pointer points to the first node.
 The search algorithm moves the two pointers
together towards the end of the list.
Example:
15
Daata Structure &
Algorithm
Cont’
Inserting
• Before insertion into a linked list, we first apply the
searching algorithm.
• If the flag returned from the searching algorithm is false, we
will allow insertion, otherwise we abort the
insertion algorithm, because we do not allow data
with duplicate
values.
• You can insert in to a linked list at the beginning, the end,
and the middle of the list.
16
Daata Structure & Algorithm
Insert at the front (beginning)
Data structures&Algorithms
17
Steps:
⚫Allocate a new node.
⚫Insert new element values.
⚫Make the next pointer of the new node point to old
head (start).
⚫Update head (start) to point to the new node.
Daata Structure & Algorithm 17
Inserting a node at the beginning of a linked list
Cont’
Data structures&Algorithms 18
Daata Structure & Algorithm 18
Inserting at the End
Steps
⚫Allocate a new node.
⚫Set the node data values and make the next pointer
of the new node point to NULL.
⚫Make old last node’s next pointer point to the new
node.
⚫Update end to point to the new node.
Data structures&Algorithms
19
Daata Structure & Algorithm 19
Inserting a node at the end of the linked list
20
Daata Structure &
Algorithm
Deleting
21
Daata Structure & Algorithm
 Before deleting, we apply the search algorithm.
 If the flag returned from the search algorithm is
true (the node is found), we can delete the node
from the linked list. However, deletion is simpler than
insertion.
 We have only two cases: deleting the first node and
deleting any other node.
 Deletion of the last and the middle nodes can be done
Deleting the first node of a linked list
Cont’
22
Daata Structure & Algorithm
Implementation of LL using C++
Daata Structure & Algorithm
Creating a node
struct node{
int data;
node *next;
};
Note:
Self
referential
structure
means…..
23
23
Cont…
Daata Structure & Algorithm
24
Adding a node to the front (of a singly linked list)
void insert_front(int x) {
node *temp=new node;
temp->data=x;
temp->next=NULL;
if(head==NULL)
head = temp;
else
{
temp->next = head;
head = temp;
}}
24
Cont…
Daata Structure & Algorithm
Adding a node to the end (of a singly linked list)
void insert_end(int x) {
node *temp=new node;
temp->data=x;
temp->next=NULL;
if(head==NULL)
head = temp;
else
node *temp2 = head;
while(temp2->next!=NULL) {
temp2 = temp2->next; }
temp2->next = temp; }
25
25
Cont…
Daata Structure & Algorithm
Deleting a node from the front( of a singly linked list)
void delete_front() {
node *temp;
if(head==NULL)
cout <<"No data insiden";
else
temp = head;
head = head->next;
delete temp; }
26
26
• The Nodes shown on the previous slides were
singly linked list.
• A node refers only to the next node in the structure
• It is also possible to have doubly linked nodes.
• The node has a reference to the next node in the
structure and the previous node in the structure as
well.
27
Daata Structure & Algorithm
Doubly linked list
 Pointers exist between adjacent nodes in both
directions. The list can be traversed either forward
or backward. Usually two pointers are maintained
to keep track of the list, head and tail.
Cont’
28
Daata Structure & Algorithm
Circular Linked List
⚫ Circular Linked List is little more complicated linked data
structure.
⚫ In the circular linked list the previous element stores the
address of the next element and the last element stores the
address of the starting element.
⚫ The elements points to each other in a circular way which
forms a circular chain.
Daata Structure & Algorithm 29
Applications of linked lists
 A linked list is a very efficient data structure for
sorted list that will go through many operations.
 A linked list is a dynamic data structure in which
the list can start with no nodes and then grow as
new nodes are needed.
 A node can be easily deleted without moving
other nodes, as would be the case with an array.
30
Daata Structure & Algorithm
 For example, a linked list could be used to hold the
records of students in a school. Each quarter or
semester, new students enroll in the school and
some students leave or graduate.
Note: A linked list is a suitable structure if a large number
of insertions and deletions are needed, but searching a
linked list is slower than searching an array.
31
Daata Structure & Algorithm
Cont’
Advantages of Linked Lists
⚫They are a dynamic in nature which allocates the
memory when required.
⚫Insertion and deletion operations can be easily
implemented.
⚫Stacks and queues can be easily executed.
⚫Linked List reduces the access time.
Daata Structure & Algorithm
Cont’
32
32
Disadvantages of Linked Lists
⚫the memory is wasted as pointers require extra
memory for storage.
⚫No element can be accessed randomly; it has to
access each node sequentially.
⚫Reverse Traversing is difficult in linked list.
Daata Structure & Algorithm
Cont’
33
33
34
Daata Structure & Algorithm
Reading Assignment
⚫Read about the implementation of doubly and
circular LL
34
Chapter 3- Linear Data Structure
Daata Structure & Algorithm
Part 2- Stacks
35
Introduction
Daata Structure &
Algorithm
2
 Stack is an ordered group of homogeneous items of elements.
Is a simple data structure, in which insertion and deletion
occur at the one end (at the top).
Anything added to the stack goes on the “top” of the stack
Anything deleted from the stack is taken from the “top” of the
stack in the reverse order from that in which they were
inserted.
36
Cont’
3
Inserting an item referred to as pushing to the stack.
Deleting an item referred to aspopping it
from the stack.
 So,A stack is a last-in-first-out (LIFO) data
structure.
Last in-delete first
First in-delete last
Daata Structure &
Algorithm
37
Stack examples- Real world
4
Daata Structure & Algorithm 38
Stack Representation on computer memory
5
Daata Structure & Algorithm 39
Stack Operation
6
PUSH operation
Daata Structure &
Algorithm
40
Cont’
POP operation
Daata Structure &
Algorithm
7
41
8
Cont’
In general, the following are basic activities on a stack:
 push an item onto the stack
The two basic operations
pop an item from the stack
retrieve the top element of the stack,
initialize the stack,
check whether the stack is empty, and
check whether the stack is full.
Daata Structure &
Algorithm
42
Implementation of Stack
9
 To implement stack we use an array.
 Since the insertion and deletion operations on a stack are made only
at the end of the stack, using an array is efficient.
Basic stack methods
 isEmpty()
 push(item)
 pop()
 peek()
Daata Structure &
Algorithm
43
IDEA:
Push() {
if there is room {
put an item on the top of the
stack
…..}
else {
give an error
message “Stack
overflow”
} Daata Structure &
Algorithm
Push operation
10
44
Array Implementation of Stacks: Push
operation
Daata Structure &
Algorithm
Step-1: Increment the stack top by 1.
 Check whether it is always less than the Upper Limit of the stack.
 If it is less than the Upper Limit go to step-2
else
report -"Stack Overflow"
Step-2: Put the new element at the position pointed by the Top
/Stack Overflow means when the stack become
full.
11
45
Algorithm
Daata Structure &
Algorithm
int stack[upper_limit];
int top= -1; /*stack is empty*/
….
main()
{… push(item);
…..}
push(int item){
top = top + 1;
if(top < upper_limit)
stack[top] = item; /*step-1 &
2*/ else
cout<<"Stack
Overflow"; }
12
46
IDEA:
Pop(){
if stack not empty {
remove the top item from the
stack
}
else{
give an error message
}
}
Daata Structure &
Algorithm
13
POP operation
47
Step-1: If the Stack is empty then give the alert
"Stack underflow" and
quit; else go to step-2
Step-2: a) Hold the value for the element pointed by the
top
b)Put a NULL value instead
c)Decrement the TOP by 1
Daata Structure &
Algorithm
14
Array Implementation of Stacks: POP operation
48
int pop(){
if(top==-1){
Daata Structure &
Algorithm
cout<<"Stack Underflown";
return -1;
}else
{int
t=stack[top]; top
--;
return t;} }
NB: /tack underflow means when the stack become
empty.
Algorith
m 15
49
16
 To reverse a word. You push a given word to stack - letter by
letter - and then pop letters from the stack.
 An "undo" mechanism in text editors; this operation is
accomplished by keeping all text changes in a stack.
Undo/Redo stacks in Excel or Word.
 Language processing : space for parameters and local variables is
created internally using a stack. compiler's syntax check for matching
braces is implemented by using stack.
 A garage that is only one car wide. To remove the first car in we
have to take out all the other cars in after it.
 Back/Forward stacks on browsers.
Daata Structure &
Algorithm
Application of Stack: Real time
50
17
Stack can be used to:
Infix to Postfix Transformation
Memory management
 During the execution of recursive programs
Implementing function or method calls
Convert Decimal to Binary
……………and so on.
Daata Structure &
Algorithm
Application of Stack more…
51
Infix to Postfix
Conversion
Daata Structure &
Algorithm
18
Revision on expression
⚫Expressions have operators (+, -, *, /, etc) and
operands (numbers, variables)
⚫In everyday use, we write the operators
in between the operands like
“4 + 5” means “add 4 and 5”…. called infix notation
⚫No reason why we couldn’t write the two operands
first,
then the operator like
“4 5 +” would mean “add 4 and 5”…called postfix 52
Why Post fix?
Does not require parentheses
Some calculators make you type in that way
Easy to process by a program
• Example
1 2 + 7 * 2 %...........has no parentheses
(3 + (5 / 3) * 6) – 4 ……..has
parentheses
Daata Structure &
Algorithm
Cont’
19
53
⚫It is common to use infix notation for our day to day work.
But in computer
system, postfix notation is widely used.
⚫As computer scientist, postfix notation has important in stack.
So, arithmetic expressions can be convert into form of
postfix notation
 4 + 5 is infix notation
 4 5 + is postfix notation
Daata Structure &
Algorithm
20
Cont’
54
⚫Rules:
 Operands immediately go directly to output/postfix.
 Operators are pushed into the stack (including parenthesis)
 Check to see if stack top operator is less than current operator
 If the top operator is less than, push the current operator onto
stack.
 If the top operator is greater than or equal the current, pop top
operator and push to postfix expression , push current
operator onto stack
Daata Structure &
Algorithm
21
Cont’
55
Priority : * /..Same
Priority : + -..Same
Priority : (
If we encounter a right parenthesis, pop from
stack until we get matching left parenthesis.
Do not write parenthesis in postfix
expression.
Daata Structure &
Algorithm
22
Cont’
56
Check: 3 + 2 * 4=?
23
ab c * +
a +b
ab +
a + b *c
ab + c *
Daata Structure &
Algorithm
a * b +c
ab * c +
(a + b )
*c
Eg1:Infix ExpressionEquivalent Postfix
Expression
57
24
((A + B) * C) / (D - E)
C
A B
D E
*
+
/
-
C
A B
D E
*
+
/
-
A B + C * D E-/
Daata Structure &
Algorithm
Eg-2: Convert this into postfix
expression
58
25
Eg-3: 6 3 + 2 * = ?
Step 1:Push 6 into
stack Step 2:push 3
into stack Step 3:apply
+(3+6=9)
Step 4:push the result into
stack Step 5:push 2 into stack
Step 6:apply *(2 * 9=18)
So, the result is 18(6 3 + 2 * =
18)
6
3
6
2
9
18
9
How to Evaluate postfix expressions using
stack?
Daata Structure &
Algorithm
59
Infix
Daata Structure &
Algorithm
a) A + B * C - D / E
b) + B * C - D / E A
c) B * C - D / E + A
d) * C - D / E + A B
e) C - D / E + * A B
f) - D / E + * A B C
g) - D / E + A B C *
h) - D / E A B C *+
i) D / E - A B C *+
j) / E - A B C *+D
K) E - / A B C *+D
l) A B C *+D E
A B C *+D E-/
Infix to Postfix Eg-
4 26
A + B * C - D / E
Stack(bot->top)
Postfix
60
Memory management
Daata Structure &
Algorithm
27
⚫ 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.
61
Chapter 3-Linear Data Structure
part 3- Queues
Daata Structure & Algorithm 62
Definition
• Like a stack, special kind of linear data structure
• Stores a set of elements in a particular order
• Unlike stack, queue use the FIRST IN FIRST
OUT( FIFO) principle
It means that the first element inserted is the first one to
be removed
 One of the queue end is called front and the other end is
called rear.
Types of Queue
• Simple Queue
• Circular Queue
• Priority 2
Daata Structure & Algorithm 63
Simple Queue
• It is the most basic queue in which the insertion of an item is
done at the front of the queue and deletion takes place at the
end of the queue.
 Additions (insertions or enqueue) are done at the rear only
 Removals (deletions or dequeue) are made from the front
only.
3
Daata Structure & Algorithm 64
Example 1: Bus station
Remove a person from the
queue
Bus
Stop
front
rear
rear rear rear rear
Daata Structure & Algorithm 65
Bus
Stop
front
rear
rear rear
Cont
’
Daata Structure & Algorithm 66
Cont
’
Bus
Stop
front
rear
rear
Daata Structure & Algorithm 67
Cont
’
Add a person to the queue
A queue is a FIFO (First-In, First-Out)
list.
Bus
Stop
Front
rear
Rear
Daata Structure & Algorithm 68
Example-
2
Daata Structure & Algorithm 69
70
Other examples
 Software queues are similar to physical ones: like queuing
at
 The supermarket
 Airport Security Check
 The bank,
 Cinemas, etc.
Daata Structure & Algorithm
Features
A list structure with two access points called the front
and
rear.
All insertions (enqueue) occur at the rear and
deletions (dequeue) occur at the front.
Varying length (dynamic).
Homogeneous
components
71
Daata Structure & Algorithm
Operations
Operation Content of
queue
Enqueue(B)
B
Enqueue(C) B, C
Dequeue() C
Enqueue(G) C, G
Enqueue (F) C, G, F
Dequeue() G, F
Enqueue(A) G, F, A
B
B
C
C
C
G
C
G
F
G
F
G
F
A
Daata Structure & Algorithm 72
Operations…
4 1 3
1 4 1 3
5 1 4 1 3
5 1 4
5 1 4 1
5 1
enqueue(1);
enqueue(5);
dequeue();
dequeue();
dequeue();
Rear Front
Given the following Queue, how
will it change when we apply the
given operations?
73
Daata Structure & Algorithm
Circular
Queue
• A circular queue is a special case of a simple queue in which
the
last member is linked to the first.
• The last node is connected to the first node.
• That is why it is called circular
• The first location is viewed after the last one.
• Overflow occurs when all the locations are filled.
74
Daata Structure & Algorithm
75
Operations
• enQueue(insertion): used to insert an element into the
circular queue. In a circular queue, the new element is
always inserted at Rear position.
Check whether queue is Full :
 Check ((rear == SIZE-1 && front == 0) | | (rear == front-1))
– If it is full then display Queue is full.
– If queue is not full then, check:
if (rear == SIZE – 1 && front != 0)
if it is true then set rear=0 and insert element.
Daata Structure & Algorithm
76
Cont
…
• deQueue(deletion) used to delete an element
from the circular queue.
• In a circular queue, the element is always deleted
from front position.
1. Check whether queue is Empty means check (front==-1).
2.If it is empty then display Queue is empty. If queue is not
empty then step 3
3. Check if (front==rear) if it is true then set front=rear= -1
else check if (front==size-1), if it is true then set front=0
and return the element.
Daata Structure & Algorithm
77
Priority
Queue
 A priority is the extension queue. It is a collection of
elements such that each element has been assigned a priority
and
the items are removed from the queue according to the
priority.
 An element of higher priority is processed before any
element of lower priority.
 Two elements with the same priority are processed
according to the order in which they were added to the
Daata Structure & Algorithm
Cont
’
Ascending Priority Queue: Collection of items into which item
can be inserted arbitrarily & the smallest item can be removed.
Descending Priority Queue: Collection of items into which item
can be inserted arbitrarily & the largest item can be removed.
78
Daata Structure & Algorithm
79
Queue
Applications
• A queue data structure is generally used in scenarios where
the FIFO approach has to be implemented.
 In operating systems to manage resources
 Handling hardware or real-time systems interrupts
 Handling website traffic
 Maintaining the playlist in media players
Daata Structure & Algorithm
80
Cont
’
 Shared resources management (system
programming)
 Access to the processor;
 Access to the peripherals such as disks and
printers.
 Application programs:
 Simulations;
 Packet Forwarding in Routers
 Message queue in Windows
Daata Structure & Algorithm
81
Cont
…
 Event-driven simulation. [ customers in a line, colliding
particles ]
 Numerical computation. [ reducing roundoff error ]
 Data compression. [ Huffman codes ]
 Graph searching. [ Dijkstra's algorithm, Prim's algorithm ]
 Number theory. [ sum of powers ]
 Artificial intelligence. [ A* search ]
Daata Structure & Algorithm
82
Cont…
 Statistics. [ online median in data stream ]
 Computer networks. [ web cache ]
 Discrete optimization. [ bin packing, scheduling
]
 Spam filtering. [ Bayesian spam filter ]
Daata Structure & Algorithm
83
Array implementation of queue
• During implementation the following points are
undertaking.
 Enqueue: add a new item at the rear
 Dequeue: remove a item from the front
 isEmpty: check whether the queue is empty or not
 isFull: Check whether the queue is full or not
 Size: return the number of items in the queue
 Peek: return the front item
Daata Structure & Algorithm
84
Insertion of
elements
int
queue[n];
Enqueue()
{ int val;
if (rear == n - 1)
"Queue Overflow“
else {
if (front == -
1) front=0;
rear++;
queue[rear] = val; Daata Structure & Algorithm
85
Deletion of
elements
Dequeue() {
if (front == - 1 | | front > rear)
{ “Queue Underflow "
}
else {
cout<<queue[front] <<endl;
front++;; }
Daata Structure & Algorithm
86
Chcek the status of the queue
• Check whether the queue is empty
boolean isEmpty()
{
return (rear == front);//front=rear=-1
}
• check whether the queue is full
boolean isFull() {
return size() == queue.length-1;// queue size =maximum
size
}
Daata Structure & Algorithm
87
• Read about priority and circular queue
implementation !
Daata Structure & Algorithm
Thank you!
Daata Structure &
Algorithm
28
88

Chapter 3- Linear Data Structure (linked list stack,queue).pptx

  • 1.
    Chapter Three-Linear DataStructure 1 Daata Structure & Algorithm Part 1-LINKED LISTS
  • 2.
    o A linkedlist is a linear data structure, in which the elements are not stored at contiguous memory locations. o The elements in a linked list are linked using pointers o It is self-referential structure. o It is a collection of elements called nodes,  A node stores two types of fields: o Data items and a pointer/link . 2 Daata Structure & Algorithm Introduction
  • 3.
    o The datafield holds the actual elements on the list o The pointer field contains the address of the next node in the list- Singly linked list o The pointer field contains the address of the previous node in the list - doubly linked list Cont ’ 3 Daata Structure & Algorithm
  • 4.
    o Let’s Store12, 34, 40 and 56 using linked list o First Create four different nodes then create link How to access the first element? Cont ’ 100 300 400 12 300 34 400 40 500 56 NULL 500 100 head 4 Daata Structure & Algorithm
  • 5.
    o In linkedlist, flexible space use by dynamically allocating space for each element as needed. o Successive elements are connected by pointers and last element points to NULL. o This implies that one need not know the size of the list in advance. Can change memory during execution.  So, memory is efficiently utilized compared to array. 5 Daata Structure & Algorithm Cont ’
  • 6.
    • The figurebelow shows a linked list called scores that contains four elements. • And also shows an example of an empty linked list. 6 Daata Structure & Algorithm
  • 7.
    Array Vs Linked List Both an array and a linked list are representations of a list of items in memory. The only difference is the way in which the items are linked together. Array:  Sequential mapping  Elements are fixed distance apart.  Makes insertion or deletion at any arbitrary position in an array a costly operation.  Randomly accessing any element…. Etc. 7 Daata Structure & Algorithm
  • 8.
    Linked List: Not necessarythat the elements be at a fixed distance apart An element is required to be linked with a previous element of the list Suitable for Inserting/deleting an element. Done by storing the address of the next element 8 Daata Structure & Algorithm Cont ’
  • 9.
  • 10.
    Cont ’  Like arraya linked list must have a name.  The name of a linked list is the name of the head pointer that points to the first node of the list. 10 Daata Structure & Algorithm
  • 11.
    Linked list operations Thefollowing are the basic operations supported by a list. ⚫Display − Displays the complete list. ⚫Search − Searches an element using the given key. ⚫Insertion − Adds an element at the beginning of the list. ⚫Deletion − Deletes an element at the beginning of the list. Deletes an element using the given key. Daata Structure & Algorithm 11
  • 12.
    Revision on Pointers Datastructures&Algorithms 12 ⚫A pointer is a variable that points to another variable. ⚫This means that a pointer holds the memory address of another variable. ⚫ The pointer does not hold a value in the traditional sense; instead, it holds the address of another variable. ⚫A pointer "points to" that other variable by holding a copy of its address. Daata Structure & Algorithm 12
  • 13.
    Display the contentof list Steps: ⚫ Set a temporary pointer to point to the same thing as the start pointer. ⚫ If the pointer points to NULL, display the message "End of list" and stop. ⚫ Otherwise, display the data values of the node pointed to by the start pointer. ⚫ Make the temporary pointer point to the same thing as the next pointer of the node it is currently indicating. ⚫ Jump back to step 2. Daata Structure & Algorithm 13
  • 14.
    Searching operation onLinked List 14 Daata Structure & Algorithm  Since nodes in a linked list have no names, we use two pointers, pre (for previous) and cur (for current).  At the beginning of the search, the pre pointer is null and the cur pointer points to the first node.  The search algorithm moves the two pointers together towards the end of the list.
  • 15.
  • 16.
    Inserting • Before insertioninto a linked list, we first apply the searching algorithm. • If the flag returned from the searching algorithm is false, we will allow insertion, otherwise we abort the insertion algorithm, because we do not allow data with duplicate values. • You can insert in to a linked list at the beginning, the end, and the middle of the list. 16 Daata Structure & Algorithm
  • 17.
    Insert at thefront (beginning) Data structures&Algorithms 17 Steps: ⚫Allocate a new node. ⚫Insert new element values. ⚫Make the next pointer of the new node point to old head (start). ⚫Update head (start) to point to the new node. Daata Structure & Algorithm 17
  • 18.
    Inserting a nodeat the beginning of a linked list Cont’ Data structures&Algorithms 18 Daata Structure & Algorithm 18
  • 19.
    Inserting at theEnd Steps ⚫Allocate a new node. ⚫Set the node data values and make the next pointer of the new node point to NULL. ⚫Make old last node’s next pointer point to the new node. ⚫Update end to point to the new node. Data structures&Algorithms 19 Daata Structure & Algorithm 19
  • 20.
    Inserting a nodeat the end of the linked list 20 Daata Structure & Algorithm
  • 21.
    Deleting 21 Daata Structure &Algorithm  Before deleting, we apply the search algorithm.  If the flag returned from the search algorithm is true (the node is found), we can delete the node from the linked list. However, deletion is simpler than insertion.  We have only two cases: deleting the first node and deleting any other node.  Deletion of the last and the middle nodes can be done
  • 22.
    Deleting the firstnode of a linked list Cont’ 22 Daata Structure & Algorithm
  • 23.
    Implementation of LLusing C++ Daata Structure & Algorithm Creating a node struct node{ int data; node *next; }; Note: Self referential structure means….. 23 23
  • 24.
    Cont… Daata Structure &Algorithm 24 Adding a node to the front (of a singly linked list) void insert_front(int x) { node *temp=new node; temp->data=x; temp->next=NULL; if(head==NULL) head = temp; else { temp->next = head; head = temp; }} 24
  • 25.
    Cont… Daata Structure &Algorithm Adding a node to the end (of a singly linked list) void insert_end(int x) { node *temp=new node; temp->data=x; temp->next=NULL; if(head==NULL) head = temp; else node *temp2 = head; while(temp2->next!=NULL) { temp2 = temp2->next; } temp2->next = temp; } 25 25
  • 26.
    Cont… Daata Structure &Algorithm Deleting a node from the front( of a singly linked list) void delete_front() { node *temp; if(head==NULL) cout <<"No data insiden"; else temp = head; head = head->next; delete temp; } 26 26
  • 27.
    • The Nodesshown on the previous slides were singly linked list. • A node refers only to the next node in the structure • It is also possible to have doubly linked nodes. • The node has a reference to the next node in the structure and the previous node in the structure as well. 27 Daata Structure & Algorithm Doubly linked list
  • 28.
     Pointers existbetween adjacent nodes in both directions. The list can be traversed either forward or backward. Usually two pointers are maintained to keep track of the list, head and tail. Cont’ 28 Daata Structure & Algorithm
  • 29.
    Circular Linked List ⚫Circular Linked List is little more complicated linked data structure. ⚫ In the circular linked list the previous element stores the address of the next element and the last element stores the address of the starting element. ⚫ The elements points to each other in a circular way which forms a circular chain. Daata Structure & Algorithm 29
  • 30.
    Applications of linkedlists  A linked list is a very efficient data structure for sorted list that will go through many operations.  A linked list is a dynamic data structure in which the list can start with no nodes and then grow as new nodes are needed.  A node can be easily deleted without moving other nodes, as would be the case with an array. 30 Daata Structure & Algorithm
  • 31.
     For example,a linked list could be used to hold the records of students in a school. Each quarter or semester, new students enroll in the school and some students leave or graduate. Note: A linked list is a suitable structure if a large number of insertions and deletions are needed, but searching a linked list is slower than searching an array. 31 Daata Structure & Algorithm Cont’
  • 32.
    Advantages of LinkedLists ⚫They are a dynamic in nature which allocates the memory when required. ⚫Insertion and deletion operations can be easily implemented. ⚫Stacks and queues can be easily executed. ⚫Linked List reduces the access time. Daata Structure & Algorithm Cont’ 32 32
  • 33.
    Disadvantages of LinkedLists ⚫the memory is wasted as pointers require extra memory for storage. ⚫No element can be accessed randomly; it has to access each node sequentially. ⚫Reverse Traversing is difficult in linked list. Daata Structure & Algorithm Cont’ 33 33
  • 34.
    34 Daata Structure &Algorithm Reading Assignment ⚫Read about the implementation of doubly and circular LL 34
  • 35.
    Chapter 3- LinearData Structure Daata Structure & Algorithm Part 2- Stacks 35
  • 36.
    Introduction Daata Structure & Algorithm 2 Stack is an ordered group of homogeneous items of elements. Is a simple data structure, in which insertion and deletion occur at the one end (at the top). Anything added to the stack goes on the “top” of the stack Anything deleted from the stack is taken from the “top” of the stack in the reverse order from that in which they were inserted. 36
  • 37.
    Cont’ 3 Inserting an itemreferred to as pushing to the stack. Deleting an item referred to aspopping it from the stack.  So,A stack is a last-in-first-out (LIFO) data structure. Last in-delete first First in-delete last Daata Structure & Algorithm 37
  • 38.
    Stack examples- Realworld 4 Daata Structure & Algorithm 38
  • 39.
    Stack Representation oncomputer memory 5 Daata Structure & Algorithm 39
  • 40.
  • 41.
  • 42.
    8 Cont’ In general, thefollowing are basic activities on a stack:  push an item onto the stack The two basic operations pop an item from the stack retrieve the top element of the stack, initialize the stack, check whether the stack is empty, and check whether the stack is full. Daata Structure & Algorithm 42
  • 43.
    Implementation of Stack 9 To implement stack we use an array.  Since the insertion and deletion operations on a stack are made only at the end of the stack, using an array is efficient. Basic stack methods  isEmpty()  push(item)  pop()  peek() Daata Structure & Algorithm 43
  • 44.
    IDEA: Push() { if thereis room { put an item on the top of the stack …..} else { give an error message “Stack overflow” } Daata Structure & Algorithm Push operation 10 44
  • 45.
    Array Implementation ofStacks: Push operation Daata Structure & Algorithm Step-1: Increment the stack top by 1.  Check whether it is always less than the Upper Limit of the stack.  If it is less than the Upper Limit go to step-2 else report -"Stack Overflow" Step-2: Put the new element at the position pointed by the Top /Stack Overflow means when the stack become full. 11 45
  • 46.
    Algorithm Daata Structure & Algorithm intstack[upper_limit]; int top= -1; /*stack is empty*/ …. main() {… push(item); …..} push(int item){ top = top + 1; if(top < upper_limit) stack[top] = item; /*step-1 & 2*/ else cout<<"Stack Overflow"; } 12 46
  • 47.
    IDEA: Pop(){ if stack notempty { remove the top item from the stack } else{ give an error message } } Daata Structure & Algorithm 13 POP operation 47
  • 48.
    Step-1: If theStack is empty then give the alert "Stack underflow" and quit; else go to step-2 Step-2: a) Hold the value for the element pointed by the top b)Put a NULL value instead c)Decrement the TOP by 1 Daata Structure & Algorithm 14 Array Implementation of Stacks: POP operation 48
  • 49.
    int pop(){ if(top==-1){ Daata Structure& Algorithm cout<<"Stack Underflown"; return -1; }else {int t=stack[top]; top --; return t;} } NB: /tack underflow means when the stack become empty. Algorith m 15 49
  • 50.
    16  To reversea word. You push a given word to stack - letter by letter - and then pop letters from the stack.  An "undo" mechanism in text editors; this operation is accomplished by keeping all text changes in a stack. Undo/Redo stacks in Excel or Word.  Language processing : space for parameters and local variables is created internally using a stack. compiler's syntax check for matching braces is implemented by using stack.  A garage that is only one car wide. To remove the first car in we have to take out all the other cars in after it.  Back/Forward stacks on browsers. Daata Structure & Algorithm Application of Stack: Real time 50
  • 51.
    17 Stack can beused to: Infix to Postfix Transformation Memory management  During the execution of recursive programs Implementing function or method calls Convert Decimal to Binary ……………and so on. Daata Structure & Algorithm Application of Stack more… 51
  • 52.
    Infix to Postfix Conversion DaataStructure & Algorithm 18 Revision on expression ⚫Expressions have operators (+, -, *, /, etc) and operands (numbers, variables) ⚫In everyday use, we write the operators in between the operands like “4 + 5” means “add 4 and 5”…. called infix notation ⚫No reason why we couldn’t write the two operands first, then the operator like “4 5 +” would mean “add 4 and 5”…called postfix 52
  • 53.
    Why Post fix? Doesnot require parentheses Some calculators make you type in that way Easy to process by a program • Example 1 2 + 7 * 2 %...........has no parentheses (3 + (5 / 3) * 6) – 4 ……..has parentheses Daata Structure & Algorithm Cont’ 19 53
  • 54.
    ⚫It is commonto use infix notation for our day to day work. But in computer system, postfix notation is widely used. ⚫As computer scientist, postfix notation has important in stack. So, arithmetic expressions can be convert into form of postfix notation  4 + 5 is infix notation  4 5 + is postfix notation Daata Structure & Algorithm 20 Cont’ 54
  • 55.
    ⚫Rules:  Operands immediatelygo directly to output/postfix.  Operators are pushed into the stack (including parenthesis)  Check to see if stack top operator is less than current operator  If the top operator is less than, push the current operator onto stack.  If the top operator is greater than or equal the current, pop top operator and push to postfix expression , push current operator onto stack Daata Structure & Algorithm 21 Cont’ 55
  • 56.
    Priority : */..Same Priority : + -..Same Priority : ( If we encounter a right parenthesis, pop from stack until we get matching left parenthesis. Do not write parenthesis in postfix expression. Daata Structure & Algorithm 22 Cont’ 56
  • 57.
    Check: 3 +2 * 4=? 23 ab c * + a +b ab + a + b *c ab + c * Daata Structure & Algorithm a * b +c ab * c + (a + b ) *c Eg1:Infix ExpressionEquivalent Postfix Expression 57
  • 58.
    24 ((A + B)* C) / (D - E) C A B D E * + / - C A B D E * + / - A B + C * D E-/ Daata Structure & Algorithm Eg-2: Convert this into postfix expression 58
  • 59.
    25 Eg-3: 6 3+ 2 * = ? Step 1:Push 6 into stack Step 2:push 3 into stack Step 3:apply +(3+6=9) Step 4:push the result into stack Step 5:push 2 into stack Step 6:apply *(2 * 9=18) So, the result is 18(6 3 + 2 * = 18) 6 3 6 2 9 18 9 How to Evaluate postfix expressions using stack? Daata Structure & Algorithm 59
  • 60.
    Infix Daata Structure & Algorithm a)A + B * C - D / E b) + B * C - D / E A c) B * C - D / E + A d) * C - D / E + A B e) C - D / E + * A B f) - D / E + * A B C g) - D / E + A B C * h) - D / E A B C *+ i) D / E - A B C *+ j) / E - A B C *+D K) E - / A B C *+D l) A B C *+D E A B C *+D E-/ Infix to Postfix Eg- 4 26 A + B * C - D / E Stack(bot->top) Postfix 60
  • 61.
    Memory management Daata Structure& Algorithm 27 ⚫ 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. 61
  • 62.
    Chapter 3-Linear DataStructure part 3- Queues Daata Structure & Algorithm 62
  • 63.
    Definition • Like astack, special kind of linear data structure • Stores a set of elements in a particular order • Unlike stack, queue use the FIRST IN FIRST OUT( FIFO) principle It means that the first element inserted is the first one to be removed  One of the queue end is called front and the other end is called rear. Types of Queue • Simple Queue • Circular Queue • Priority 2 Daata Structure & Algorithm 63
  • 64.
    Simple Queue • Itis the most basic queue in which the insertion of an item is done at the front of the queue and deletion takes place at the end of the queue.  Additions (insertions or enqueue) are done at the rear only  Removals (deletions or dequeue) are made from the front only. 3 Daata Structure & Algorithm 64
  • 65.
    Example 1: Busstation Remove a person from the queue Bus Stop front rear rear rear rear rear Daata Structure & Algorithm 65
  • 66.
  • 67.
  • 68.
    Cont ’ Add a personto the queue A queue is a FIFO (First-In, First-Out) list. Bus Stop Front rear Rear Daata Structure & Algorithm 68
  • 69.
  • 70.
    70 Other examples  Softwarequeues are similar to physical ones: like queuing at  The supermarket  Airport Security Check  The bank,  Cinemas, etc. Daata Structure & Algorithm
  • 71.
    Features A list structurewith two access points called the front and rear. All insertions (enqueue) occur at the rear and deletions (dequeue) occur at the front. Varying length (dynamic). Homogeneous components 71 Daata Structure & Algorithm
  • 72.
    Operations Operation Content of queue Enqueue(B) B Enqueue(C)B, C Dequeue() C Enqueue(G) C, G Enqueue (F) C, G, F Dequeue() G, F Enqueue(A) G, F, A B B C C C G C G F G F G F A Daata Structure & Algorithm 72
  • 73.
    Operations… 4 1 3 14 1 3 5 1 4 1 3 5 1 4 5 1 4 1 5 1 enqueue(1); enqueue(5); dequeue(); dequeue(); dequeue(); Rear Front Given the following Queue, how will it change when we apply the given operations? 73 Daata Structure & Algorithm
  • 74.
    Circular Queue • A circularqueue is a special case of a simple queue in which the last member is linked to the first. • The last node is connected to the first node. • That is why it is called circular • The first location is viewed after the last one. • Overflow occurs when all the locations are filled. 74 Daata Structure & Algorithm
  • 75.
    75 Operations • enQueue(insertion): usedto insert an element into the circular queue. In a circular queue, the new element is always inserted at Rear position. Check whether queue is Full :  Check ((rear == SIZE-1 && front == 0) | | (rear == front-1)) – If it is full then display Queue is full. – If queue is not full then, check: if (rear == SIZE – 1 && front != 0) if it is true then set rear=0 and insert element. Daata Structure & Algorithm
  • 76.
    76 Cont … • deQueue(deletion) usedto delete an element from the circular queue. • In a circular queue, the element is always deleted from front position. 1. Check whether queue is Empty means check (front==-1). 2.If it is empty then display Queue is empty. If queue is not empty then step 3 3. Check if (front==rear) if it is true then set front=rear= -1 else check if (front==size-1), if it is true then set front=0 and return the element. Daata Structure & Algorithm
  • 77.
    77 Priority Queue  A priorityis the extension queue. It is a collection of elements such that each element has been assigned a priority and the items are removed from the queue according to the priority.  An element of higher priority is processed before any element of lower priority.  Two elements with the same priority are processed according to the order in which they were added to the Daata Structure & Algorithm
  • 78.
    Cont ’ Ascending Priority Queue:Collection of items into which item can be inserted arbitrarily & the smallest item can be removed. Descending Priority Queue: Collection of items into which item can be inserted arbitrarily & the largest item can be removed. 78 Daata Structure & Algorithm
  • 79.
    79 Queue Applications • A queuedata structure is generally used in scenarios where the FIFO approach has to be implemented.  In operating systems to manage resources  Handling hardware or real-time systems interrupts  Handling website traffic  Maintaining the playlist in media players Daata Structure & Algorithm
  • 80.
    80 Cont ’  Shared resourcesmanagement (system programming)  Access to the processor;  Access to the peripherals such as disks and printers.  Application programs:  Simulations;  Packet Forwarding in Routers  Message queue in Windows Daata Structure & Algorithm
  • 81.
    81 Cont …  Event-driven simulation.[ customers in a line, colliding particles ]  Numerical computation. [ reducing roundoff error ]  Data compression. [ Huffman codes ]  Graph searching. [ Dijkstra's algorithm, Prim's algorithm ]  Number theory. [ sum of powers ]  Artificial intelligence. [ A* search ] Daata Structure & Algorithm
  • 82.
    82 Cont…  Statistics. [online median in data stream ]  Computer networks. [ web cache ]  Discrete optimization. [ bin packing, scheduling ]  Spam filtering. [ Bayesian spam filter ] Daata Structure & Algorithm
  • 83.
    83 Array implementation ofqueue • During implementation the following points are undertaking.  Enqueue: add a new item at the rear  Dequeue: remove a item from the front  isEmpty: check whether the queue is empty or not  isFull: Check whether the queue is full or not  Size: return the number of items in the queue  Peek: return the front item Daata Structure & Algorithm
  • 84.
    84 Insertion of elements int queue[n]; Enqueue() { intval; if (rear == n - 1) "Queue Overflow“ else { if (front == - 1) front=0; rear++; queue[rear] = val; Daata Structure & Algorithm
  • 85.
    85 Deletion of elements Dequeue() { if(front == - 1 | | front > rear) { “Queue Underflow " } else { cout<<queue[front] <<endl; front++;; } Daata Structure & Algorithm
  • 86.
    86 Chcek the statusof the queue • Check whether the queue is empty boolean isEmpty() { return (rear == front);//front=rear=-1 } • check whether the queue is full boolean isFull() { return size() == queue.length-1;// queue size =maximum size } Daata Structure & Algorithm
  • 87.
    87 • Read aboutpriority and circular queue implementation ! Daata Structure & Algorithm
  • 88.
    Thank you! Daata Structure& Algorithm 28 88