DS Unit - 3 Ppts
DS Unit - 3 Ppts
• Linear list.
• One end is called top.
• Other end is called bottom.
• Additions to and removals from the top end
only.
Dr.L.Lakshmi 1
STACK ADT
A stack is a Last In First Out (LIFO) data structure in which all insertions and
deletions are takes place at one end, called the top.
Stack maintains a variable called top, which keeps track of the top most element in
the stack.
In the stack, the elements are removed in the reverse order of that in which they were
added to the stack that is last element inserted is to be deleted first.
Dr.L.Lakshmi 2 2
STACK ADT
Example 1:
When the elements are inserted in the order as A,B,C,D then the size
of the stack is 4 and the top most element in the stack is D.
When deletion operation is performed on stack continuously then the order in which
the elements are deleted is D,C,B,A.
Dr.L.Lakshmi 3 3
STACKS
Standard operations:
IsEmpty … return true iff stack is empty
IsFull … return true iff stack has no remaining capacity
Top … return top element of stack
Push … add an element to the top of the stack
Pop … delete the top element of the stack
Dr.L.Lakshmi 4
STACKS
ADT Stack is
Object: a finite ordered list with 0 / more elements.
Functions:
for all stack belong Stack, item belong element, maxStackSize belongs
positive integer.
Stack Create(maxStackSize)::= create an empty stack whose maximum
size is maxStackSize
Boolean IsFull(stack ,maxStackSize)::=
if (number of elements in stack == maxStazkSize) return TRUE else
return FALSE
Stack Push(stack) ::=
if (IsFull(stack)) stackFull else insert item into top of stack and return
Boolean IsEmpty(stack) ::=
if (stack == CreateS(maxStackSize)) return TRUE else return FALSE
Element Pop(stack) ::=
if (IsEmpty(stack)) return else remove and return the element at the top of
the stack Dr.L.Lakshmi 5
STACK ADT
IMPLEMENTATION
Stack can be implemented in two ways:
1. using arrays
2. using linked list
Dr.L.Lakshmi 6 6
STACK ADT USING ARRAYS
STACK IMPLEMENTATION USING ARRAYS
Procedure:
Initialize the stack by assigning -1 to the top variable to indicate that the array based
stack is empty.
A top is an integer value, which contains the array index for the top of the stack.
Dr.L.Lakshmi 7 7
STACK ADT USING ARRAYS
Algorithm for inserting an element into the stack
push()
1. if top>=size then
print “stack is full”
2. else
read item
top=top+1
stack[top]=item
endif
3. stop
Overflow occurs when we are trying to insert an item into a stack which is full.
If the top value reaches to maximum size of the stack then items cannot
be inserted into the stack i.e. stack is full.
Dr.L.Lakshmi 9
STACK ADT USING ARRAYS
Algorithm for deleting an element from the stack
pop()
1. if top = -1 then
print “stack is empty”
2. else
1. item = stack[top]
2. top=top-1
3.endif
4.stop
Takeout the element from the location where the top is pointing and
store it in the variable then decrement top by one.
Dr.L.Lakshmi 10 10
STACK ADT USING ARRAYS
POP Functon
void pop()
{
if(top==-1)
printf("\n stack is empty(underflow)\n");
else
printf("the pop element is:%d",stack[top]);
top--;
}
Dr.L.Lakshmi 11
STACK ADT USING ARRAYS
Algorithm for displaying an elements of the stack
traversal() void display()
{
1. if top = -1 if(top==-1)
1.print “stack empty” {
2. else
1. for(i = top; i >= 0;i--) printf("\n stack is empty(underflow)");
1.print “stack[i]” return
3.endif }
4. stop printf("\n the elements in stack are:\n");
for(i=top;i>=0;i--)
printf("->%d",stack[i]);
}
If the top value is -1 then the stack is empty.
If the stack is not empty, assign a top value to variable i, display the item
which is pointed at stack[i] , decrement the top value by one and repeat this
process until top becomes zero.
Dr.L.Lakshmi 13 13
STACK ADT USING LINKED LIST
Example:
The following list consists of five cells, each of which holds a data object
and a link to another cell.
Dr.L.Lakshmi 14 14
STACK ADT USING LINKED LIST
Push function POP function
void push() void pop()
{ {
struct node*temp; struct node*temp;
temp=(struct node*)malloc(sizeof(struct if(top==NULL)
node)); printf("\n stack is empty \n");
printf("\n enter data of item:"); else
scanf("%d",&temp->data); {
temp->link=top; temp=top;
top=temp; printf("popped item is %d \
} n",temp->data);
top=top->link;
free(temp);
}
}
Dr.L.Lakshmi 15 15
STACK ADT USING LINKED LIST
Traversal function
void display()
{
struct node*temp;
temp=top;
if(top==NULL)
printf("stack is empty \n");
else
{
printf("stack elements:\n");
while(temp!=NULL)
{
printf("->%d",temp->data);
temp=temp->link;
}
}
}
C program example2 , also show error simulation
Dr.L.Lakshmi 16
STACK APPLICATIONS
APPLICATIONS
Dr.L.Lakshmi 17 17
STACK APPLICATIONS
TYPES OF EXPRESSIONS
Dr.L.Lakshmi 18 18
STACK APPLICATIONS
CONVERSIONS
Dr.L.Lakshmi 19 19
STACK APPLICATIONS
Algorithm to convert infix expression to Postfix:
1.Initialize an empty stack.
2.Repeat the following process until the end of the infix expression.
Get next input token (constant, variable, arithmetic operator, left
parenthesis, right parenthesis) in the infix expression.
If the token is
A left parenthesis: Push it onto the stack.
A right parenthesis:
Pop and display stack elements until a left parenthesis is on the top of
the stack.
Pop the left parenthesis also, but do not display it.
An operator:
While the stack is nonempty and token has higher or equal priority than
the stack’s top element, pop and display.
Push token onto the stack.
An operand: Display it.
3.When the infix expression is reached to the end, pop and display stack items
until the stack is empty.
(Note: Left parenthesis in the stack has lowest priority)
Dr.L.Lakshmi 20 20
STACK APPLICATIONS
Dr.L.Lakshmi 21 21
STACK ADT
1. Algorithm for postfix conversion:
void postfix(char inf[15])
Step 1: repeat the steps a to c until inf[i]!='\0'
a. check if infix expression is opening brace push it onto stack
check if(inf[i]='(‘) push(inf[i])
b. check if infix expression is alphabetic character add it to postfix express
if(isalpha(inf[i])) pf[j++]=inf[i]
c. check if infix expression is closing brace
if(inf[i]==')')
repeat 1 to 2 until stack[top]!=opening brace
1.pf[j++]=pop()
2.x=pop()
Otherwise
repeat 1 to 2 until prec(stack[top])>=prec(inf[i])
1.pf[j++]=pop()
2.push(inf[i])
Step 2: repeat the steps a to b until top!=-1
a.pf[j++]=pop()
b.pf[j]='\0'
step 3: stop
Dr.L.Lakshmi 22 22
STACK ADT
2. Algorithm for push operation on stack:
Step 1:increment top by 1
Step 2: stack[++top]=y
Step 3:stop
Dr.L.Lakshmi 23 23
STACK ADT
Dr.L.Lakshmi 24 24
STACK APPLICATIONS
Postfix conversion function
int prec(char c)
{
if(c=='*' || c=='/')
return(5);
else if(c=='+' || c=='-')
return(3);
else if(c=='(')
return(1);
}//end of prec()
Dr.L.Lakshmi 27 27
STACK APPLICATIONS
Applications of Stacks
• Direct applications
Page-visited history in a Web browser
Undo sequence in a text editor
Chain of method calls in the Java Virtual Machine
• Indirect applications
Auxiliary data structure for algorithms
Component of other data structures
Dr.L.Lakshmi 30 30
STACK APPLICATIONS
Demonstration of Manual infix to postfix conversion
moves the addition operator to between the last two closing parentheses. This
change is made because the closing parentheses for the plus sign is the last
parenthesis.
We now have ( A ( B C * ) + )
Dr.L.Lakshmi 31
STACK APPLICATIONS
Infix Transformations
A + B * C – D / E Converts to A B C * + D E / -
Above transformation is illustrated in following figure.
Dr.L.Lakshmi 33
STACK APPLICATIONS
Evaluation of Postfix Expression
For example given expression is A B C + *
And assuming that A is 2, B is 4, and C is 6 ,
the following figure shows the evaluation of postfix expression.
Dr.L.Lakshmi
35 35
Queues
ADT Queue is
Object: a finite ordered list with 0 / more elements.
Functions:
for all queue belong Queue, item belong element, maxQueueSize belongs positive
integer.
Queue Create(maxQueueSize)::= create an empty queue whose maximum size is
maxQueueSize
Boolean IsFull(queue ,maxQueueSize)::=
if (number of elements in queue == maxQueueSize) return TRUE else return
FALSE
Queue AddQ(queue , item) ::=
if (IsFullQ(queue)) queueFull else insert item at rear of queue and return queue
Boolean IsEmptyQ(queue) ::=
if (queue == CreateQ(maxQueueSize)) return TRUE else return FALSE
Element DeleteQ(queue) ::=
if (IsEmptyQ(queue)) return else remove and return the item at front of queue
Dr.L.Lakshmi
36 36
Queues
• Linear list.
• One end is called front.
• Other end is called rear.
• Additions are done at the rear only.
• Removals are made from the front only.
Dr.L.Lakshmi 37
Bus Stop Queue
Bus
Stop
Dr.L.Lakshmi 38
Bus Stop Queue
Bus
Stop
Dr.L.Lakshmi 39
Bus Stop Queue
Bus
Stop
front rear
rear
Dr.L.Lakshmi 40
Bus Stop Queue
Bus
Stop
front rear
rear
Dr.L.Lakshmi 41
Revisit Of Stack Applications
• Applications in which the stack cannot be
replaced with a queue.
1. Parentheses matching.
2. Towers of Hanoi.
3. Switchbox routing.
4. Method invocation and return.
5. Try-catch-throw implementation.
Objectives:
Queue Operations
Queue Linked List Design
Queue Functions
Queue Demonstration
Dr.L.Lakshmi
43 43
Queues
Queue operations:
•
Data can be inserted at the rare in queue
•
Data can be deleted at front in queue
Dr.L.Lakshmi
44 44
QUEUE ADT
IMPLEMENTATION
Queue can be implemented in two ways:
1. using arrays
2. using linked list
Dr.L.Lakshmi 45 45
Queues using arrays
• We can also implement queue using arrays.
• There are mainly two functions in implementation of queue:
1) enqueue
2) dequeue
Enqueue
• An enqueue to an empty queue is placed in the first element of the array.
which becomes both front and rear.
• Subsequent enqueues are placed at the array locations following rear i.e if the
last element is stored at array location 11,the data for next enqueue is placed
in element 12.
Dr.L.Lakshmi
46 46
Queues using arrays
Dequeue
• A dequeue takes place at the front of the queue.
• As an element is deleted from the queue, the queue front is advanced to the next
location
• Fig-8 shows about physical structure of queue
Queue ary
count Max size front rare
7 17 5 11
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15]
Dr.L.Lakshmi
47 47
QUEUE USING ARRAY
1.if(front==-1)
2. print queue is empty / underflow
3. return;
4. print the element in queue are
5. for(i=front;i<=rear;i++)
6. print arr[i]
Dr.L.Lakshmi 50 50
Queues using arrays
Disavantages:
• In a queue, we delete elements at front and insert elements at rear.
• when rear reaches maximum size of an array, we can’t Insert new element though we
have space at front end of a queue.
• Therefore queue is not full because there are empty elements at the beginning of the
array. It shows queue is full.
• Fig shows array queue with last elements filled
Queue Queue
front rare
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]
[12]
Example -7 Dr.L.Lakshmi
for 51
queue using array 51
Queues Linked List
Dr.L.Lakshmi
52 52
Queues Linked List
Dequeue
• If the queue contains data, then set the front pointer to the next
item in the queue
Dr.L.Lakshmi 55 55
QUEUE USING LINKED LIST
Enqueue function
Dequeue function
1. struct node*temp;
2. if(front==NULL||rear==NULL)
3. print queue underflow
4. else
5. temp=front;
6. print deleted element temp->data
7. front=front->link
8. free(temp)
Dr.L.Lakshmi 57 57
QUEUE USING LINKED LIST
Display function
Dr.L.Lakshmi 58 58
Queues Linked List
Dr.L.Lakshmi
59 59
Circular Queues
• This disadvantage is overcome by shifting all the elements from end to the
beginning of the array
• In the above example, we shift from element 5 to 0 and 6 to 1 and so on.
• A more efficient alternative is found in circular queue
• In a circular queue, the last element is logically followed by the first element
Dr.L.Lakshmi
60 60
Circular Queues
Circular queue can be implemented in two ways
Dr.L.Lakshmi 61
Circular Queues
Circular queue using arrays
[2] [3]
Initially circular queue is
empty
[0] [5]
Dr.L.Lakshmi 62
Circular Queues
Dr.L.Lakshmi 63
Circular Queues
Dr.L.Lakshmi 64
Circular Queues
Dr.L.Lakshmi 65
Circular Queues
Circular queue using arrays
Dr.L.Lakshmi 66
Circular Queues
Dr.L.Lakshmi 67
Circular Queues
Circular queue using arrays
Dr.L.Lakshmi 69
Circular Queue
Dr.L.Lakshmi
70 70
Circular Queue
if(front == -1)
printf("\n\nCIRCULAR QUEUE IS UNDERFLOW");
else
{
a=cqueue[front];
if(front==rear)
front=rear=-1;
else
front = (front+1)%MAXSIZE;
printf("\n\nDELETED ELEMENT FROM QUEUE IS : %d ",a);
}
Dr.L.Lakshmi
71 71
Circular Queue
if(front == -1)
printf("\n\nCIRCULAR QUEUE IS UNDERFLOW");
else
{
for(i=front;i<=rear;i++)
{
printf(“ %d \t“,cqueue[i]);
}
}
Dr.L.Lakshmi 72
Circular Queue
Dr.L.Lakshmi 76 76
DEQUEUE
Dr.L.Lakshmi 77
DEQUEUE
TYPES OF DEQUE
Input restricted Deque
• Elements can be inserted only at one end.
As Queue
• When items are inserted at one end and removed at the other
end.
Dr.L.Lakshmi 79
DEQUEUE
Dequeue is also called as double ended queue and it allows user to perform
insertion and deletion from the front and rear position. And it can be easily
implemented using doubly linked list. On creating dequeue, we need to add two
special nodes at the ends of the doubly linked list(head and tail). And these two
nodes needs to be linked between each other(initially).
head tail
--------------------------- --------------------------------
| | | ---|---------->| | | |
| NULL | 0 | | | | 0 | NULL |
| | | |<----------|--- | | |
---------------------------- -------------------------------
Dr.L.Lakshmi 80 80
DEQUEUE
So, the header node goes before the first node of the queue and the trailer node
goes after the last node in the queue. To do insertion at the front position, place
the new node next to the head. And to do insertion at the rear position, place the
new node before the tail. Similarly, dequeue operation can also be performed at
the front and rear positions.
Operations
Insert a New Element From front
Insert a New Element From rear
Delete an Element From front
Delete an Element From rear
Dr.L.Lakshmi 81 81
DEQUEUE using Array
1. Algorithm for insertion at rear end:
Dr.L.Lakshmi 82 82
DEQUEUE using Array
2. Algorithm for insertion at front end:
Dr.L.Lakshmi 83 83
DEQUEUE using Array
3. Algorithm for deletion at rear end:
Dr.L.Lakshmi 84 84
DEQUEUE using Array
Algorithm for deletion at front end:
1: check if (front==-1)
Print Deletion is not possible: Dequeue is empty
return
Step 2: otherwise
Print The deleted element is a[front]
Check if(front==rear)
front=rear=-1
otherwise
front=front-1
Step 3:stop
Dr.L.Lakshmi 87 87
DEQUEUE using Linked list
3. Algorithm for deletion at front end:
Dr.L.Lakshmi 88 88
DEQUEUE using Linked list
4. Algorithm for deletion at rear end:
Dr.L.Lakshmi 89 89
DEQUEUE using Linked list
5.Algorithm for displaying the dequeue:
Step 3: stop
Dr.L.Lakshmi 90 90
APPLICATIONS OF DEQUE
Palindrome-checker
Dr.L.Lakshmi 91
APPLICATIONS OF DEQUE
• processors(multiprocessor scheduling).
• The processor gets the first element from the deque.
Dr.L.Lakshmi 93
End
Dr.L.Lakshmi 94