chapter -4 stack & queue
chapter -4 stack & queue
Stack:- is a an ordered set of items/ a data structure in which addition of new element or deletion
of existing element always takes place from one end known as top.
Push ( )
{
If there is a room {
Put an item on the top of the stack
Else
Give an error message
}
}
Pop ( )
{
If stack not empty {
return the value of the top item
remove the top item from the stack
}
else {
give an error message
}
}
CreateStack()
{
remove existing items from the stack
initialise the stack to empty
}
1
}
Stack is not in built like array and structure in C++, therefore it will be implemented in two
ways:
1. Static implementation (using arrays)
2. Dynamic implementation (using pointers/linked lists)
4.1.1 Array implementation of Stacks: PUSH & POP operations
Struct stack{ }
}; {cout<<”empty/underflow”;
If(top==n-1) top--
Top++; }
2
What is a linked list?
Linked list is a data structure in which each data item points to the
next data item. This "linking" is accomplished by keeping an address
variable (a pointer) together with each data item. This pointer is used
to store the address of the next data item in the list. The structure that
is used to store one element of a linked list is called a node. A node
has two parts: data and next address. The data part contains the
necessary information about the items of the list, the next address part
contains the address of the next node.
A NULL Pointer is used to signal the end of a list. The last node will
have NULL in its next address part.
4
Examples for casting:
int number = 9;
double result;
result = (double)number / 2;
Getting a new node:
/* allocates memory for a new node */
nodeptr getnode(void)
{
nodeptr ptr;
ptr = (nodeptr) malloc(sizeof(node_t));
return(ptr);
}
Actions Related With Linked Lists: (These will be explained in the
lecture.)
Examples:
6
Linked List implementation of Stacks: PUSH & POP operations
Struct node{ }
top=NULL; temp2->data=item;
if(top==NULL) top=temp2;
{ temp2->next=temp;
temp->data=item’ }}
7
If(top==NULL) Int item=temp->data;
{Cout<<”empty”; Top=top->next;
Temp=top; }
e.g. 4 + 5 * 5=A+B
Postfix expression:- a notation, in which the operator is written after the operands(reverse polish
notation)
e.g. 4 5 +5*=AB+
Prefix expression:- a notation, in which the operator is written before the operands(polish
notation)
e.g.+ 4 * 5 5=+AB
Computers solve arithmetic expressions by restructuring them so the order of each calculation is
embedded in the expression
8
Because the postfix notation is most suitable for a computer to calculate any expression (due
to its reverse characteristic), and is the universally accepted notation for designing Arithmetic
and Logical Unit (ALU) of the CPU (processor).
e.g add(A, B)
But in a postfix expression operands appear before the operator, so there is no need for operator
precedence and other rules. As soon as an operator appears in the postfix expression during
scanning of postfix expression the topmost operands are popped off and are calculated by
applying the encountered operator.
Any expression entered into the computer is first converted into postfix notation, stored in
stack and then calculated.
9
6*48=288
10
Total number in the queue = front-rear+1
Algorithm:-
Int n=10;
Struct queue{
int data[n];
int front,rear;
};Front=-1;rear=-1;
{ }
{front==-1; Front=front+1;
Rear==-1;} }
Else{ Return x;
if(front==n-1) }
Front=0; }
}; {rear=front=p;}
*front,*rear; Else{rear->nxt=p;
Front=rear=NULL; Rear=rear->nxt;}
Void enq(int x) }
{ Int deq()
node *p; {
Node *p;
Int x;
X=front->data;
P=front;
Front=front->nxt;
Delete p;
Return x;
14
4.2.3 Application of queue
Find the prefix and postfix notation for the following infix
expression:
(a + b – c) * (e / f) – ( g – h/i)
There is a quick way to convert from one notation to another. You start by inserting all
the implicit brackets/parentheses that determine the order of evaluation, regardless of
what notation the expression is already in. So, taking the expression above and adding
these implicit brackets gives:
This is before:
(a + b - c) * (e / f) - ( g - h/i)
15
look like (/ h i ). Do this for every operator in a bracket. So, converting the expression above
to prefix notation will give you:
And finally, removing all the parentheses gives us our final prefix notation:
- * - + a b c / e f - g / h i
Try figuring out how to get the postfix notation on your own using the rules given above. You
should get this as your answer:
a b + c - e f / * g h i / - -
Every node in the binary tree is reachable from the root node by
a unique path
A node with neither a left child nor a right child is called a leaf
16
Picture of a binary tree
a
b c
d e f
g h i j k
17
Size and depth
a
The size of a binary
tree is the number
b c
of nodes in it
d e f
This tree has size 12
g h i j k
The depth of a
l node is its distance
from the root
Balancea is at depth zero
e is at depth 2
a a
b The depth
c b of a
c e is the
d e f g binary tree
d f
hi j depth ofgits
A balanced h
i node
deepest j
binary tree An unbalanced
A binary tree is balanced Thisbinary
treeif has treedepth
every level4
above the lowest is “full” (contains 2n
nodes)
In most applications, a reasonably balanced
A binary tree is defined recursively: it consists of a root, a left
binary tree
subtree, and is desirable
a right subtree
18
To traverse (or walk) the binary tree is to visit each node in the binary
tree exactly once
Since a binary tree has three “parts,” there are six possible ways to
traverse the binary tree:
“flags”
The order in which the nodes are
visited during a tree traversal can be
easily determined by imagining there
preo attachedinord
is a “flag” to each node,post
as
To traverse
rder the tree,er
follows:A collect
A
the flags:
orde
A
r
B C B C B C
D E F G D E F G D E F G
ABDEC DBEAF DEBFG
FG CG CA
The depth of a node is the number of edges from the root to the node.
The height of a node is the number of edges from the node to the deepest leaf.
The height of a tree is a height of the root.
A full binary tree.is a binary tree in which each node has exactly zero or two
children.
A complete binary tree is a binary tree, which is completely filled, with the
possible exception of the bottom level, which is filled from left to right.
19
A complete binary tree is very special tree, it provides the best possible ratio between
the number of nodes and the height. The height h of a complete binary tree with N
nodes is at most O(log N). We can easily prove this by counting nodes on each level,
starting with the root, assuming that each level has the maximum number of nodes:
n = 1 + 2 + 4 + ... + 2h-1 + 2h = 2h+1 - 1
Advantages of trees
Trees are so useful and frequently used, because they have some very serious
advantages:
Traversals
A traversal is a process that visits all the nodes in the tree. Since a tree is a nonlinear
data structure, there is no unique traversal. We will consider several traversal
algorithms with we group in the following two kinds
depth-first traversal
breadth-first traversal
20
There are three different types of depth-first traversals,:
Pre Order traversal - visit the parent first and then left and right children;
In Order traversal - visit the left child, then the parent and the right child;
Post Order traversal - visit left child, then the right child and then the parent;
There is only one kind of breadth-first traversal--the level order traversal. This
traversal visits nodes by levels from top to bottom and from left to right.
In the next picture we demonstarte the order of node visitation. Number 1 denote the
first node in a particular traversal and 7 denote the last node.
Insertion
22
The insertion procedure is quite similar to searching. We start at the root and
recursively go down the tree searching for a location in a BST to insert a new node. If
the element to be inserted is already in the tree, we are done (we do not insert
duplicates). The new node will always replace a NULL reference.
Draw a binary search tree by inserting the above numbers from left to right.
Searching
Searching in a BST always starts at the root. We compare a data stored at the root
with the key we are searching for (let us call it as toSearch). If the node does not
contain the key we proceed either to the left or right child depending upon
comparison. If the result of comparison is negative we go to the left child, otherwise -
to the right child. The recursive structure of a BST yields a recursive algorithm.
Searching in a BST has O(h) worst-case runtime complexity, where h is the height of
the tree. Since s binary search tree with n nodes has a minimum of O(log n) levels, it
takes at least O(log n) comparisons to find a particular node. Unfortunately, a binary
serch tree can degenerate to a linked list, reducing the search time to O(n).
Deletion
23
Deletion is somewhat more tricky than insertion. There are several cases to consider.
A node to be deleted (let us call it as toDelete)
is not in a tree;
is a leaf;
has only one child;
has two children.
If toDelete is not in the tree, there is nothing to delete. If toDelete node has only
one child the procedure of deletion is identical to deleting a node from a linked list -
we just bypass that node being deleted
Deletion starategy is the following: replace the node being deleted with the largest
node in the left subtree and then delete that largest node. By symmetry, the node being
deleted can be swapped with the smallest node is the right subtree.
Draw a binary search tree by inserting the above numbers from left to right and then
show the two trees that can be the result after the removal of 11.
25