You are on page 1of 146

UNIT-1

Objectives

1. Introduction to Linear and Non Linear data structures


2. Singly Linked list, circularly linked lists, Double Linked list
3. To be able to implement Stack ADT using arrays.
4. To be able to implement Stack ADT using linked list.
5. To analyze various application of stacks.
6. To implement infix to postfix conversion.
7. To be able to implement Queue ADT using arrays.
8. To be able to implement Queue ADT using linked list.
9. To understand and implement the concept of Circular Queue.
10. To understand and implement the concept of Double Ended
Queue.

1
Data Abstraction
The basic data types includes char , int , float & double.
Some data types may be modified by keywords short , long , unsigned

Two mechanisms for grouping data together:


1. Arrays
2. Structures

Data types:

It is a collection of objects & set of operations that act on those objects.


int consists of objects
{ 0 , +1 , -1 , +2 , -2 , INT_MAX, INT_MIN }
INT_MAX : largest integer on machine
INT_MIN: smallest integer on machine
It includes in <limits.h>

2
Data Abstraction
Abstract Data Type(ADT):

It is a data type i.e, organised in such a way that the specification of the objects & the
specification of the operations on the objects is separated from the representation of the
objects & implementation of the operations.

e.g : Ada have packages


C++ have class

The functions of a data types into several categories:


1. Creator / constructor
2. Transformers
3. Observers / reporters

3
Data Abstraction
1. Creator / constructor:

These functions create a new instance of the designed type.

2. Transformers :

These functions also create an instance of the designed type generally by


using 1 / more other instances.

3. Observers / reporters:

These functions provide information about an instance of the type , but they
do not change the instance

4
PERFORMANCE ANALYSIS 1 of 4
When several algorithms can be designed for the solution of a problem, there arises the
need to determine which among them is the best. The efficiency of a program or an
algorithm is measured by computing –

• Time Complexity

• Space Complexity

5
Introduction to Linear & Non-linear
Data Structure 1 of 3
The data structure can be defined as the collection of elements and all the possible
operations which are required for those set of elements. In other words data structure will
tell us specific set of elements and corresponding set of operations.

A data structure can be defined as a way of organizing and storing data in a computer so
that it can used efficiently.

Mathematically, a data structure D is a triplet, that is, D=(d, f, a) where

D= data structure
d= a set of variables (data objects)
f= a set of functions
a= set of rules to implement the functions.

6
Introduction to Linear & Non-linear
Data Structure 2 of 3
Data Structures:
A data structure is an arrangement of data in a computer's memory or even disk
storage.

It classified into two types


1.  Linear Data Structures
2. Non Linear Data Structures

1. Linear Data Structures:


Linear data structures are those data structures in which data elements are
accessed (read and written) in sequential fashion ( one by one)

Eg: Stacks , Queues, Lists, Arrays


 
2. Non Linear Data Structures:
Non Linear Data Structures are those in which data elements are not accessed
in sequential fashion.

Eg: trees, graphs


7
Introduction to Linear & Non-linear
Data Structure 3 of 3
Types of Data Structure
 
Data Structure

Primitive Data Non Primitive


Structures Data Structures

Linear Data Non Linear Data


Eg: int, char, float
Structures Structures

Eg: array, linked


Eg: trees, graphs
list, stack, queue

8
Difference between linear and non linear
data structures
Linear DS Non Linear DS
data elements are organized a data element can be attached
sequentially and therefore they to several other data elements to
are easy to implement in the represent specific relationships
computer’s memory. that exist among them. Due to
this nonlinear structure, they
might be difficult to be
implemented in computer’s
linear memory compared to
implementing linear data
structures.

every item is related to its every item is attached with many


previous and next time. other items.
9
Difference between linear and non linear
data structures
Linear DS Non Linear DS
data is arranged in linear data is not arranged in sequence.
sequence.
data items can be traversed in a data cannot be traversed in a
single run. single run.
eg. array, stcks, linked list, queue. eg. tree, graph
implementation is easy implementation is difficult.
It contains data item and a single It contains a data item and two
link pointing to next element links left link pointing to previous
element and right link pointing to
next element

10
Difference between linear and non linear
data structures
Linear DS Non Linear DS
Syntax Syntax
Struct node Struct node
{ {
int data; int data;
struct node*link; struct node*left;
}; struct node*right;
};

11
SINGLY LINKED LIST 1 of 14
Definition of linked list

 A linked list is a linear collection of homogeneous data elements, called nodes, where
linear order is maintained by means of links or pointers.

 Each node has two parts:


 The first part contains the data (information of the element) and
 The second part contains the address of the next node (link /next pointer field) in
the list.

 Data part of the link can be an integer, a character, a String or an object of any kind.

12
SINGLY LINKED LIST 2 of 14
node
NODE
link struct Node  
{  
  int data;  
  struct Node *link;  
};   
data

LINKED LIST

Start Null

A B C D
13
SINGLY LINKED LIST 3 of 14

• Linear collection of self-referential structures, called nodes, connected by pointer


links.

• Accessed via a pointer to the first node of the list.

• Subsequent nodes are accessed via the link-pointer member stored in each node.

• Link pointer in the last node is set to null to mark the end of the list.

• Data stored dynamically – each node is created as necessary.

• Length of a list can increase or decrease.

• Becomes full only when the system has insufficient memory to satisfy dynamic
storage allocation requests.

14
SINGLY LINKED LIST 4 of 14

TYPES OF LINKED LISTS

1. Singly linked list


• Begins with a pointer to the first node
• Terminates with a null pointer
• Only traversed in one direction

2. Circular, singly linked list


• Pointer in the last node points back to the first node

3. Doubly linked list


• Two “start pointers”- first element and last element
• Each node has a forward pointer and a backward pointer
• Allows traversals both forwards and backwards

4. Circular, doubly linked list


• Forward pointer of the last node points to the first node and backward pointer
of the first node points to the last node

15
SINGLY LINKED LIST 5 of 14

A singly linked list, or simply a linked list, is a linear collection of data items. The linear
order is given by means of POINTERS. These types of lists are often referred to as
linear linked list.

• Each item in the list is called a node.

• Each node of the list has two fields:

Information- contains the item being stored in the list.


Next address- contains the address to the next item in the list.

• The last node in the list contains NULL pointer to indicate that it is the end of the list.
 

16
SINGLY LINKED LIST 6 of 14

OPERATIONS

• Creation of a node
• Insertions
• Deletions
• Traversing the list

Structure of a node: data link


 

struct node
{
int data;
struct node *next;
};
 

17
SINGLY LINKED LIST 7 of 14

CREATION OF A NODE:

Inittially first=NULL last=NULL

struct node *cur;

cur=(struct node*)malloc(size of(struct node));

Read cur->data

cur->link=NULL

18
SINGLY LINKED LIST 8 of 14
Algorithm for creating a node

Step 1: if the list is empty then first==NULL


Step 2: Create a new node
cur= (struct node*) malloc (sizeof (struct node));

Step 3: Read the content of node


Step 4: Assign new node link to NULL
cur->link=NULL
Step 5: Assign new node to first & last node
first=cur
last=cur
Step 6: If the list is not empty call insert function
insert ()
Step 7 : Stop
19
SINGLY LINKED LIST 9 of 14
INSERTION:

How do we place elements in the list: Usually, there are 4 cases we can use:

• at the beginning

• at the end of the list

• after a given element

• before a given element

20
SINGLY LINKED LIST 10 of 14
Case 1 : at the beginning Pseudo code:
1. Inserting at beginning of list.
2. if (first! = NULL)
3. {
4. Cur=(struct node*) malloc
(sizeof(struct node))
5. Read cur->data
6. Cur->lnk=first
7. First=cur
8. }

21
SINGLY LINKED LIST 11 of 14
Case 2 : end of the list Pseudo code:
1. Inserting at end of list.
2. if (first! = NULL)
3. {
4. Cur=(struct node*) malloc
(sizeof(struct node))
5. Read cur->data
6. Next=first
7. While(next!=NULL)
8. {
1. Prev=next;
2. Next=next->link;
}
Cur->link=prev->link;
9. prev->link=cur
10. }

22
SINGLY LINKED LIST 12 of 14
Case 3 : after a given element Pseudo code:
1. Inserting at end of list.
2. if (first! = NULL)
3. {
4. Cur=(struct node*) malloc
(sizeof(struct node))
5. Read cur->data
6. Next=first
7. while(next!=NULL)
8. {
9. if(next->data = = key)
10. break;
11. else
12. next=next->link;
13. }
14. cur -> link = next->link;
15. next->link = cur;
16. }

23
SINGLY LINKED LIST 12 of 14
Case 4 : Before a given element
Pseudo code:
1. Inserting at end of list.
2. if (first! = NULL)
3. {
4. Cur=(struct node*) malloc
(sizeof(struct node))
5. Read cur->data
6. Next=first
7. while(next!=NULL)
8. {
9. if(next->data = = key)
10. break;
11. else
1. { prev=next
12. next=next->link; }
13. }
14. cur -> link = prev->link;
15. prev->link = cur;
16. }
24
SINGLY LINKED LIST 12 of 14
DELETION: Removing an element from the list, without destroying the integrity of the list
itself.

When we delete a node we logically remove the node from the list by changing links and
physically remove it from heap

1)deletion from beginning of list


2)deletion at middle of list
3)deletion at end of list

25
SINGLY LINKED LIST 13 of 14
DELETION at the beginning of list:

Pseudo code:
1. If (first==NULL)
2. Print list is empty
3. else if(first->link==NULL)
4. Deleted element first->data
5. first-=NULL
6. Else
7. {
8. cur=first
9. First=cur->link
10. Deleted element cur->data
11. Free(cur)
12. Cur=NULL

26
SINGLY LINKED LIST 13 of 14
DELETION at the end of list:
Pseudo code:
1. If (first==NULL)
2. Print list is empty
3. Else
4. {
5. cur=first
6. While(cur->link!=NULL)
7. Prev=cur
8. Deleted element is cur-.>data
9. Free(cur)
10. Prev->link=NULL

27
SINGLY LINKED LIST 13 of 14
DELETION at a given position other than first or last Pseudo code:
1. If (first==NULL)
2. Print list is empty
3. Else
4. {
5. Read position of
deletion
6. next=first
7. While(c<pos) {
8. Cur=next
9. Next=next->link
10. C++
11. }
12. Cur->link=next->link
13. Deleted element is
next-.>data
14. Free(next)
15. next->link=NULL

28
SINGLY LINKED LIST 14 of 14
TRAVERSAL:

Pseudo code:
1. temp = first;
2. while(temp!=NULL)
3. {
4. print temp->data;
5. temp = temp->link;
6. }

29
C program example1 , also show error simulation
SINGLY LINKED LIST 14 of 14
Concatenation of two single linked lists:
struct node *concat( struct node *start1,struct node *start2)
{
struct node *ptr;
if(start1==NULL)
{
start1=start2;
return start1;
}
if(start2==NULL)
return start1;
ptr=start1;
while(ptr->link!=NULL)
ptr=ptr->link;
ptr->link=start2;
return start1;
}

30
CIRCULARLY LINKED LIST
Insertion at the front of Circular linked list
Procedure for insertion a node at the beginning of list
Step1. Create the new node
Step2. Set the new node’s next to itself (circular!)
Step3. If the list is empty, return new node.
Step4. Set our new node’s next to the front.
Step5. Set tail’s next to our new node.
Step6. Return the end of the list.

31
CIRCULARLY LINKED LIST
Insertion in the middle of the Circular linked list

32
CIRCULARLY LINKED LIST
Insertion at the end of Circular linked list
Procedure for insertion a node at the end of list
Step1. Create the new node
Step2. Set the new node’s next to itself (circular!)
Step3. If the list is empty,return new node.
Step4. Set our new node’s next to the front.
Step5. Set tail’s next to our new node.
Step6. Return the end of the list.

33
CIRCULARLY LINKED LIST
Deletion In Circular linked list
There are three situation for Deleting element in list.
1.Deletion at beginning of the Circular linked list.
2.Deletion at the middle of the Circular linked list.
3.Deletion at the end of the Circular linked list.

34
CIRCULARLY LINKED LIST
1.Deletion at beginning of the Circular linked list.

After Deletion

35
CIRCULARLY LINKED LIST
Deletion at beginning in Circular linked list
Pseudo code:

node=start->next;
ptr=start;
if(i==0)
{
printf("\n List is empty");
exit(0);
}
ptr->next=node->next;
free(node);

36
CIRCULARLY LINKED LIST
Deletion at the middle of the Circular linked list

After Deletion

37
CIRCULARLY LINKED LIST
Deletion at location in Circular linked list
Pseudo code:

if(node_no==delete_no) {
ptr->next=node->next;
free(node);
flag=1;
break;
}
else {
ptr=ptr->next;
node=node->next;
}
node_no++;
count--; }
if(flag==0) {
printf("\n Position not found");

38
CIRCULARLY LINKED LIST
Deletion at the end of the Circular linked list

After Deletion

39
CIRCULARLY LINKED LIST

Deletion at Last Node


Pseudo code:

node=start->next;
ptr=start; count=i;
if(i==0) {
printf("\n List is empty"); exit(0);
}
while(count) { node_no++;
ptr=ptr->next; node=node->next;
count--; } node=start->next;
ptr=start;
while(node_no!=1) {
node_no--;
ptr=ptr->next;
node=node->next;
} if(node_no==1) { ptr->next=node-
>next; free(node);}

40
C program example: 2 , also show error simulation
CIRCULARLY LINKED LIST
A circularly linked list, or simply circular list, is a linked list in which the last
node is always points to the first node. This type of list can be build just by
replacing the NULL pointer at the end of the list with a pointer which points to the
first node. There is no first or last node in the circular list.
 
Advantages:
 Any node can be traversed starting from any other node in the list.
There is no need of NULL pointer to signal the end of the list and hence, all
pointers contain valid addresses.
In contrast to singly linked list, deletion operation in circular list is simplified as
the search for the previous node of an element to be deleted can be started from
that item itself.

41
DOUBLY LINKED LIST
 In a singly linked list one can move from the header node to any node in one
direction only (left-right).

 A doubly linked list is a two-way list because one can move in either direction
i.e., either from left to right or from right to left.

 It maintains two links or pointers. Hence, it is called as doubly linked list.

PREV DATA NEXT

 Where, DATA field stores the element


Structure
or of the PREV
data, node contains the address of its
previous node, NEXT contains the address of its next node.

42
DOUBLY LINKED LIST
struct node
{
  int data;
  struct node *next; // Pointer to next node in DLL
  struct node *prev; // Pointer to previous node in DLL 
};

43
DOUBLY LINKED LIST
Advantages over singly linked list

1) A DLL can be traversed in both forward and backward direction.

2) The delete operation in DLL is more efficient if pointer to the node to be deleted is
given.

In singly linked list, to delete a node, pointer to the previous node is needed. To get this
previous node, sometimes the list is traversed. In DLL, we can get the previous node using
previous pointer.

Disadvantages over singly linked list

1) Every node of DLL Require extra space for an previous pointer. It is possible to
implement DLL with single pointer though.

2) All operations require an extra pointer previous to be maintained. For example, in


insertion, we need to modify previous pointers together with next pointers. For example in
following functions for insertions at different positions, we need 1 or 2 extra steps to set
previous pointer.
44
DOUBLY LINKED LIST
In this type of liked list each node holds two-pointer field. Pointers exist between
adjacent nodes in both directions. The list can be traversed either forward or backward

45
DOUBLY LINKED LIST
Creating a New Node
Pseudo code:

ptr=(node*)malloc(sizeof(node));
ptr->info=item;
if(*start==NULL) {
ptr->prev = ptr->next = NULL ;
*start = *end = ptr ;
}
else {
ptr->prev = *end;
(*end)->next = ptr ;
ptr->next= NULL;
(*end)=ptr;
}

46
DOUBLY LINKED LIST
Insertion in doubly linked list
There are three situation for inserting element in list.
1.Insertion at the front of list.
2.Insertion in the middle of the list.
3.Insertion at the end of the list.

1.Insertion at the front of list

47
DOUBLY LINKED LIST
Insert at front of the list Algorithm
Pseudo code: InsertAtFrontDll(info,prev,next,start,end
)
ptr=(node*)malloc(sizeof(node)); 1.create a new node and address in
ptr->info=item; assigned to ptr.
if(*start==NULL) 2.check[overflow] if(ptr=NULL)
{ write:overflow and exit
*start=ptr; 3.set Info[ptr]=item;
*end=ptr; 4.if(start=NULL)
} set prev[ptr] = next[ptr] = NULL
else set start = end = ptr
{ else
ptr->prev = NULL; set prev[ptr] = NULL
ptr->next=*start; next[ptr] = start
(*start)->prev=ptr; set prev[start] = ptr
*start=ptr; set start = ptr [end if]
} 5.Exit.

48
DOUBLY LINKED LIST
2.Insertion in the middle of the list

49
DOUBLY LINKED LIST
2.Insertion in the middle of the list
Pseudo code:
ptr=(node*)malloc(sizeof(node));
ptr->info=item;
loc = *start ;
if(*start==NULL) {
ptr->prev = ptr->next = NULL ;
*start = *end = ptr ; }
else if(i<=size) {
while(n != i) {
loc=loc->next;
n++;
}
ptr->next = loc->next ;
ptr->prev = loc ;
(loc->next)->prev = ptr ;
loc->next = ptr ;   
}
else{
ptr->prev = *end;
(*end)->next = ptr ;
ptr->next= NULL;
(*end)=ptr; }}
50
DOUBLY LINKED LIST
3.Insertion at the end of the list

51
DOUBLY LINKED LIST

Insert at the end of Dllist


Pseudo code:
ptr=(node*)malloc(sizeof(node));
ptr->info=item;
if(*start==NULL)
{
ptr->prev = ptr->next = NULL ;
*start = *end = ptr ;
}
else
{
ptr->prev = *end;
(*end)->next = ptr ;
ptr->next= NULL;
(*end)=ptr;
}
C program example: 3 , also show error
simulation
52
STACKS

• Linear list.
• One end is called top.
• Other end is called bottom.
• Additions to and removals from the top end
only.

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

 Any insertions or deletions should be based upon the value of top.

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

Basic Stack Operations:


push :To insert an item into stack
pop :To delete an item from stack
traversal :To display an items
isFull :To know whether the stack is full or not
isEmpty :To know whether the stack is empty or not

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

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

56
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 57
STACK ADT
IMPLEMENTATION
Stack can be implemented in two ways:
1. using arrays
2. using linked list

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

 Each time data is pushed or popped, top is incremented or Decremented accordingly,


to keep track of the current top of the stack.

 Stacks implemented as arrays are useful if a fixed amount of data is to be used.

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

The first step of this algorithm checks for an overflow condition.

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.

Otherwise top is incremented by one and item is inserted into


60 the stack. 60
STACK ADT USING ARRAYS
Push Functon
void push()
{
int ele;
if(top==SIZE-1)
{
printf("\n stack is full(overflow)\n");
return;
}
else
{
printf("enter the element to push:");
scanf("%d",&ele);
top++;
stack[top]=ele;
}

61
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

The first step of this algorithm checks for underflow condition.

If the top value is -1 then stack is known as underflow or empty.

Takeout the element from the location where the top is pointing and
store it in the variable then decrement top by one.

62 62
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--;
}

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

C program example1 , also show error simulation


64 64
STACK ADT USING LINKED LIST
STACK IMPLEMENTATION USING LINKED LIST

 Implementing stacks as linked lists provides a feasibility on the number of nodes by


dynamically growing stacks, as a linked list is a dynamic data structure.

 The stack can grow or shrink as the program demands it to.

 Disadvantage of using an array to implement a stack or queue is the wastage of


space.

 A variable top always points to top element of the stack.

 top = NULL specifies stack is empty.

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

66 66
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);
}
}

67 67
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
68
STACK APPLICATIONS

APPLICATIONS

• Stacks are used in conversion of infix to postfix expression.

• Stacks are also used in evaluation of postfix expression.

• Stacks are used to implement recursive procedures.

• Stacks are used in compiler design.

69 69
STACK APPLICATIONS

TYPES OF EXPRESSIONS

Arithmetic expressions can be represented in three ways:

Infix notation: The operator is in between the two operands.


Examples: A+B 2+3

Prefix (Polish notation): The operator precedes the operands.


Examples: +AB +23

Postfix (Reverse Polish Notation): The operator follows the operands.


Examples: AB+ 23+

70 70
STACK APPLICATIONS

CONVERSIONS

Consider the infix expression: 2 + 3 * (5 – 7) / 9


Let us insert implicit parentheses
(2 + ((3 * (5 – 7)) / 9))

Transfer the operators to the beginning of parentheses


(+ 2 (/ (* 3 (– 5 7)) 9))
Remove the parentheses: + 2 / * 3 – 5 7 9
This is the equivalent prefix expression.

Transfer the operators to the end of parentheses


(2 ((3 (5 7 –) *) 9 /) +)
Remove the parentheses: 2 3 5 7 – * 9 / +
This is the equivalent postfix expression.

71 71
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)
72 72
STACK APPLICATIONS

73 73
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
74 74
STACK ADT
2. Algorithm for push operation on stack:
Step 1:increment top by 1
Step 2: stack[++top]=y
Step 3:stop
 
3. Algorithm for pop operation on stack:
Step 1:return stack[top]
Step 2: decrement top by 1
Step 3:stop

4. Algorithm for finding precedence of operators :


Step 1:check if (c=='*' || c=='/' || c=='%')
return(5)
step 2:check if (c=='+' || c=='-')
return(3)
Step 3:if(c=='(')
return(1)
step 4:stop

75 75
STACK ADT

5. Algorithm for main function :


Step 1:start
Step 2: read infix expression
Step 3:call postfix(infix)
Step 4:print postfix expression result
Step 5:stop

76 76
STACK APPLICATIONS
Postfix conversion function

void postfix(char inf[15]) else


{ {
char x; while(prec(stack[top]>=prec(inf[i])))
for(i=0;inf[i]!='\0';i++) pf[j++]=pop();
{ push(inf[i]);
if(inf[i]=='(') }
push(inf[i]);
else if(isalpha(inf[i])) }//end of for
pf[j++]=inf[i]; while(top!=-1)
else if(inf[i]==')') {
{ pf[j++]=pop();
while(stack[top]!='(') pf[j]='\0';
pf[j++]=pop(); }//end of postfix()
x=pop(); }
}
void push(int y) int pop()
{ {
stack[++top]=y; return(stack[top--]);
}//end of push() }//end of pop() 77
STACK APPLICATIONS
recedence function

int prec(char c)
{
if(c=='*' || c=='/')
return(5);
else if(c=='+' || c=='-')
return(3);
else if(c=='(')
return(1);
}//end of prec()

C program example3 , also show error simulation


78
STACK APPLICATIONS

Algorithm to evaluate Postfix Expression:


1.Initialize an empty stack.
2.Do

Get next token (constant, arithmetic operator) in postfix expression.

If token is an operand, push it on the stack.

If token is an operator do the following:

Pop top two values from the stack. (If the stack does not contain two items,
report error.)

Apply operator token to these two values.

Push the resulting value onto the stack.
3.Continue the process until the end of the expression is encountered.
4.The value of the expression is on the top of the stack (and stack should
contain only this value).

79 79
STACK APPLICATIONS

C program example4 , also show error simulation


80 80
STACK APPLICATIONS
Postfix evaluation function case '-':push(a-b);
void evaluate(char pf[15]) break;
{ case '*':push(a*b);
float a,b,x; break;
for(i=0;pf[i]!='\0';i++) case '/':push(a/b);
{ break;
if(isalpha(pf[i])) default: printf("invalid operator\n");
{ }//end of switch
printf("enter value of %c",pf[i]); }//end of else
scanf("%f",&x); }//end of for
push(x); printf("value of expression %f",stack[top--]);
}//end of if }//end of evaluate()
else//if operator
{ void push(float y)
b=pop(); {
a=pop(); stack[++top]=y;
switch(pf[i]) }
{ float pop()
case '+':push(a+b); {
break; return(stack[top--]);
81
}
STACKS

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

82 82
STACK APPLICATIONS
Demonstration of Manual infix to postfix conversion

Step 1 A + B * C by placing paranthesis results


(A+(B*C))
Step 2 moves the multiply operator after C
( A + (B C *) )
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 * ) + )

Finally ,step 3 removes the parentheses A B C * +

83
STACK APPLICATIONS
Infix Transformations
A + B * C – D / E Converts to A B C * + D E / -
Above transformation is illustrated in following figure.

Example 4 converting infix expression to postfix expression 84


STACK APPLICATIONS

Evaluation of Postfix Expression


• In evaluation of postfix expression, it is the operands that are pushed on to the
stack. The postfix expression is scanned from left to right. Any operands
encountered are pushed on to the stack. When an operator is encountered, the
top two operands are popped from the stack. The operation is performed and
the result is pushed back on to the stack. In the end, the final value is popped
from the stack and returned.

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

Example 5 evaluation of postfix expression


86
Queues
Definition
• A queue is a order / linear list in which data can be inserted at one end, called
the rear, and deleted from the other end, called the front. It is a first in–first
out (FIFO) restricted data structure.
• A queue is same as
Ex: 1)a line of people waiting for a bus at bus station.
2)a list of waiting jobs to be processes by a computer.
• The fig-1 below shows two examples of a queue.
A) A queue of people
B) a computer queue

87 87
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
88 88
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.

89
Bus Stop Queue

Bus
Stop

front rear rear rear rear


rear

90
Bus Stop Queue

Bus
Stop

front rear rear


rear

91
Bus Stop Queue

Bus
Stop

front rear
rear

92
Bus Stop Queue

Bus
Stop

front rear
rear

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

• Application in which the stack may be replaced


with a queue.
1. Rat in a maze.
• 2. Results in finding shortest path to exit.
94
Queues

Objectives:

Queue Operations
Queue Linked List Design
Queue Functions
Queue Demonstration

95 95
Queues

Queue operations:

The two basic queue operations:


1)Insertion operation (enqueue)
2)Deletion operation (dqueue)


Data can be inserted at the rare in queue

Data can be deleted at front in queue

96 96
QUEUE ADT
IMPLEMENTATION
Queue can be implemented in two ways:
1. using arrays
2. using linked list

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

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

FIG-8 Physical structure

99 99
QUEUE USING ARRAY

Adding / enqueu function


1 if(rear==SIZE-1)
2 print queue is full / overflow
3 return;
4 else
5 rear++;
6 enter the element to ENQUEUE
7 if(front==-1)
8 front++;
100 100
QUEUE USING ARRAY

Deleting /dequeue function


1. if(front==-1)
2. print queue is empty / underflow
3. return;
4. else
5. print the DEQUEUE element arr[front]
6. if(front==rear)
7. front=rear=-1
8. else
9. front++
101 101
QUEUE USING ARRAY
displayfunction

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]

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

 Fig array queue with last elements filled

Example -7 for 103


queue using array 103
Queues Linked List

• There two basic functions in queue using linked list


1) Enqueue
2) Dequeue
Enqueue
• when we insert data into a queue, the queue’s front and rear pointers must be
set to the new node
• When we insert data into a queue with data already in it, we must point both
the link field in the last node and rear pointer to the new node.
• If insert is successful, it returns true else if no memory left for the new node, it
returns false
• Fig shows enqueue

104 104
Queues Linked List

Dequeue

• If the queue is empty, we have underflow and return false

• We first ensure that the queue contains data.

• If the queue contains data, then set the front pointer to the next
item in the queue

• If we dequeue the last item, the queue front pointer


automatically becomes null pointer. it also assigns null pointer
to link filed of the last node.

• Fig shows dequeue implementation.


105 105
Queues Linked List

FIGURE -6 Enqueue Example


106 106
QUEUE USING LINKED LIST
struct node
{
int data;
struct node*link;
};
struct node*front=NULL,*rear=NULL;

107 107
QUEUE USING LINKED LIST

Enqueue function

1. struct node *temp


2. temp=(struct node*)malloc(sizeof(struct node))
3. print enter the element to be inserted
4. temp->data=ele
5. temp->link=NULL
6. if(rear==NULL||front==NULL)
7. front=temp
8. else
9. rear->link=temp
10. rear=temp
108 108
QUEUE USING LINKED LIST

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)

109 109
QUEUE USING LINKED LIST

Display function

1. struct node *temp


2.temp=front
3. if(front==NULL||rear==NULL)
4. print queue is empty
5. else
6. while(temp!=NULL)
7. print temp->data
8. temp=temp->link
Example -6 for queue using linked list

110 110
Queues Linked List

FIGURE -7 Dequeue Examples

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

112 112
Circular Queues
Circular queue can be implemented in two ways

1.Circular queue using arrays


2.Circular queue using linked lists

113
Circular Queues
Circular queue using arrays

Insertion into the circular queue

[2] [3]
Initially circular queue is
empty

front= -1 [1] [4]


rear= -1

[0] [5]

114
Circular Queues

front=0 and rear=0 front=0 and rear=1

115
Circular Queues

front=0 and rear=2 front=0 and rear=3

116
Circular Queues

front=0 and rear=4 front=0 and rear=5

117
Circular Queues
Circular queue using arrays

Deletion from the circular queue

front=1 and rear=5 front=2 and rear=5

118
Circular Queues

front=3 and rear=5 Front=4 and rear=5

119
Circular Queues
Circular queue using arrays

Insertion from the circular queue

front=4 and rear=0 front=4 and rear=1


120
Circular Queues

front=4 and rear=2 front=4 and rear=3

121
Circular Queue

Insert an element into a Circular Queue


if(front ==(rear+1)%MAXSIZE)
printf("\n\nCIRCULAR QUEUE IS OVERFLOW");
else
{
 if(front==-1)
   front=rear=0;
   else
   rear=(rear+1)%MAXSIZE;
   cqueue[rear]=item;
   }

122 122
Circular Queue

Delete an element from a 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);
}

123 123
Circular Queue

Display the content of a circular queue

if(front == -1)
printf("\n\nCIRCULAR QUEUE IS UNDERFLOW");
else
{
for(i=front;i<=rear;i++)
{
printf(“ %d \t“,cqueue[i]);
}
}

124
Circular Queue

Insert an element into a Circular Queue using linked list


void enqueue()
{
struct node*temp;
temp=(struct node*)malloc(sizeof(struct node));
printf("\n enter the element to be inserted");
scanf("%d",&temp->data);
temp->link=NULL;
if(count==0)
front=temp;
else
rear->link=temp;
rear=temp;
rear->link=front;
count++;
}
125
Circular Queue
Delete an element from a circular queue
void dequeue()
{
struct node*temp;
if(front==NULL||rear==NULL)
printf("\n queue underflow");
else
{ count--;
if(front==rear)
{ printf("\n deleted element is %d",front->data);
free(front);
front=rear=NULL;
} else
{ temp=front;
printf("\n deleted element is %d\n",temp->data);
front=front->link;
rear->link=front;
free(temp);
}}}
126
Circular Queue
Display the content of a circular queue
void display()
{
int i; struct node*temp;
if(front==NULL||rear==NULL)
printf("\n queue is empty");
else
{
if(count==0)
printf("\n queue is empty");
else
{
temp=front;
for(i=0;i<count;i++)
{
printf("->%d",temp->data);
temp=temp->link;
}
printf(")\n");
} } } 127
DEQUEUE
A double-ended queue is an abstract data type similar to an simple queue, it allows
you to insert and delete from both sides means items can be added or deleted
from the front or rear end.

128 128
DEQUEUE

• A Deque or deck is a double-ended queue.


• Allows elements to be added or removed on either the
ends.

129
DEQUEUE

TYPES OF DEQUE
 Input restricted Deque
• Elements can be inserted only at one end.
• Elements can be removed from both the ends.

 Output restricted Deque


• Elements can be removed only at one end.
• Elements can be inserted from both the ends.

130
DEQUEUE

Deque as Stack and Queue


As STACK
• When insertion and deletion is made at the same side.

As Queue
• When items are inserted at one end and removed at the other
end.

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

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

133 133
DEQUEUE using Array
1. Algorithm for insertion at rear end:
 
Step 1: check if(front==-1)
front++
rear++
read the element to insert a[rear]
count++;
Step 2: check if(rear>=SIZE-1)
print Insertion is not possible, overflow!!!
return
Step 3: Increment the rear by 1
read the element to insert a[rear]
count++;
Step 4:stop

134 134
DEQUEUE using Array
2. Algorithm for insertion at front end:
 
Step 1: check if(front==-1)
front++
rear++
read the element to insert a[rear]
count++
Step 2: check if(rear>=SIZE-1)
print Insertion is not possible, overflow!!!
return
Step 3: Repeat the steps a to d until i>0
a[i]=a[i-1]
read the element to insert a[i]
count++
rear++;
Step 4:stop

135 135
DEQUEUE using Array
3. Algorithm for deletion at rear end:
 
Step 1: check if (front==-1)
Print Deletion is not possible: Dequeue is empty
return
Step 2: otherwise
Print The deleted element is a[rear]
Check if(front==rear)
front=rear=-1
otherwise
rear=rear-1
Step 3:stop
 

136 136
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
 
5.Algorithm for displaying the dequeue:
 
Step 1: check if (front==-1)
Print Dequeue is empty
return
Step 2: otherwise
Repeat step a until i<=rear (i=front)
Print a[i] 137 137
Step 3:stop
DEQUEUE using Linked list
ALGORITHM:
Initialize the front and rear nodes with NULL values
struct node *front=NULL,*rear=NULL,*cur,*temp
 
1. Algorithm for insertion at rear end:
 
Step 1: Create a new node
cur=(struct node*) malloc (sizeof (struct node))
Step 2: Read the content of node (cur->data)
Step 3: Assign new node right link to NULL
cur->right=NULL
Step 4: Assign new node to front & rear node
Check if(rear==NULL&&front==NULL)
rear=front=cur
Step 5: otherwise
rear->right=cur
cur->left=rear
rear=cur
Step 6:stop
138 138
DEQUEUE using Linked list
2. Algorithm for insertion at front end:
 
Step 1: Create a new node
cur=(struct node*) malloc (sizeof (struct node))
Step 2: Read the content of node (cur->data)
Step 3: Assign new node right link to NULL
cur->right=NULL
Step 4: Assign new node to front & rear node
Check if(rear==NULL&&front==NULL)
rear=front=cur
Step 5: otherwise
cur->right=front
front->left=cur
front=cur
Step 6:stop

139 139
DEQUEUE using Linked list
3. Algorithm for deletion at front end:
 
Step 1: check if(front==NULL)
Print deQueue is empty
Step 2: otherwise
Check if(front==rear)
Print Deleted data is front->data
front=rear=NULL
Step 3: otherwise
temp=front;
print Deleted data is temp->data
front=front->right
front->left=NULL
free(temp)
Step 4: stop

140 140
DEQUEUE using Linked list
4. Algorithm for deletion at rear end:
 
Step 1: check if(front==NULL)
Print deQueue is empty
Step 2: otherwise
Check if(front==rear)
Print Deleted data is rear->data
front=rear=NULL
Step 3: otherwise
temp=rear;
print Deleted data is temp->data
if(front==rear)
front=rear=NULL
rear=rear->left
rear->right=NULL
free(temp)
Step 4: stop

141 141
DEQUEUE using Linked list
5.Algorithm for displaying the dequeue:
 
Step 1: check if(front==NULL)
Print deQueue is empty
Step 2: otherwise
temp=front;
repeat steps a-b until temp!= NULL
a. printf("<-%d ->",temp->data)
b. temp=temp->right;

Step 3: stop

142 142
APPLICATIONS OF DEQUE

Palindrome-checker

143
APPLICATIONS OF DEQUE

A-Steal job scheduling algorithm


• The A-Steal algorithm implements task scheduling for several
• processors(multiprocessor scheduling).
• The processor gets the first element from the deque.
• When one of the processor completes execution of its own threads
• it can steal a thread from another processor.
• It gets the last element from the deque of another processor and
• executes it.

144
APPLICATIONS OF DEQUE

OTHER APPLICATIONS OF DEQUE

• Undo-Redo operations in Software applications.

145
End

146

You might also like