SDOT Training Day2
SDOT Training Day2
• Stack can be defined as a Data Structure that serves as saving the data in a
particular fashion.
• In linear data structures like array and linked list a user is allowed to insert
or delete any element to and from any location respectively.
• However, in a Stack both, insertion and deletion, is permitted at one end
only.
• A Stack works on the LIFO (Last In – First Out) basis, i.e , the first element
that is inserted in the stack would be the last to be deleted; or the last
element to be inserted in the stack would be the first to be deleted..
Stacks
push() pop()
top()
Stack
Stack is a A Last In First Out (LIFO) data structure.
Primary operations: Push and Pop
push()
• Add an element to the top of the stack
pop()
• Remove the element from the top of the stack
Additionally, few more methods also defined in typical implementations:
Size()
isEmpty()
If Full()
Stack
-1 Stack is Empty
0 Only one element in
Stack
N-1 Stack is Full
N Overflow state of Stack
Stack
TIME COMPLEXITY
METHO TIME
D COMPLEXITY
push() O(1)
pop() O(1)
top() O(1)
search() O(n)
Stack implementation in C
#include<stdio.h> else {
#include<stdlib.h> a[++top] = x;
#define MAX 1000 printf("%d pushed into stack",x);
return true;
bool isEmpty(); }
bool push(int); }
int pop();
int peek(); int pop()
void display(); {
if (top < 0) {
int a[MAX]; // Maximum size of Stack printf("Stack Underflow");
int top = -1; return 0;
}
bool isEmpty() else {
{ int x = a[top--];
return (top < 0); return x;
} }
}
bool push(int x)
{
if (top >= (MAX - 1)) {
printf("Stack Overflow \n");
return false;
}
Stack implementation in C (contd)
int peek() int main()
{ {
if (top < 0) { int ch,key;
printf("Stack Underflow"); do
return 0; {
} printf("Enter the option to perform\n");
else { printf("1. Push\t2. Pop\t3. Peek\t4. Display\t5. Exit \n");
int x = a[top]; scanf("%d",&ch);
return x; switch(ch)
} {
} case 1:
scanf("%d",&key);
void display() push(key);
{ break;
int i = top; case 2:
if (i < 0) { printf("%d is popped from stack", pop());
printf("Stack is empty \n"); break;
} case 3:
else { printf("%d is the top element in stack", peek());
while(i>=0) break;
printf("%d\n",a[i--]); case 4:
} display();
} break;
case 5:
break;
default:
printf("Invalid option...\n");
break;
}
}while(ch < 5);
}
Stack implementation in Java
import java.util.Scanner; int pop()
class Stack { {
static final int MAX = 1000; if (top < 0) {
int top; System.out.println("Stack Underflow");
int a[] = new int[MAX]; // Maximum size of Stack return 0;
}
boolean isEmpty() else {
{ int x = a[top--];
return (top < 0); return x;
} }
Stack() }
{ int peek()
top = -1; {
} if (top < 0) {
System.out.println("Stack Underflow");
boolean push(int x) return 0;
{ }
if (top >= (MAX - 1)) { else {
System.out.println("Stack Overflow"); int x = a[top];
return false; return x;
} }
else { }
a[++top] = x;
System.out.println(x + " pushed into stack");
return true;
}
}
Stack implementation in Java (contd)
void display() Exit \n");
{ ch = sc.nextInt();
int i = top; switch(ch)
System.out.println("Top is "+i); {
if (i < 0) { case 1:
System.out.println("Stack is empty"); int key = sc.nextInt();
} s.push(key);
else { break;
System.out.println("Inside else Top is "+i); case 2:
while(i>=0) System.out.println(s.pop() + " is popped from stack");
System.out.println(a[i--]); break;
} case 3:
} System.out.println(s.peek() + " is the top element in stack");
break;
} case 4:
s.display();
class StackinJava { break;
public static void main(String args[]) case 5:
{ break;
Stack s = new Stack(); default:
Scanner sc = new Scanner(System.in); System.out.println("Invalid option...");
int ch; break;
do }
{ }while(ch < 5);
System.out.println("Enter the option to perform\n"); }
System.out.println("1. Push\t2. Pop\t3. Peek\t4. Display\t5. }
Stack implementation using collections in Java
import java.util.Stack; System.out.println(s.peek() + " is the top element in
import java.util.Scanner; stack");
class StackinCollections{ break;
public static void main(String[] args) case 4:
{ System.out.println("Stack = "+s);
Stack <Integer> s = new Stack<Integer>(); break;
Scanner sc = new Scanner(System.in); case 5:
int ch; break;
do default:
{ System.out.println("Invalid option...");
System.out.println("Enter the option to perform\n"); break;
System.out.println("1. Push\t2. Pop\t3. Peek\t4. }
Display\t5. Exit \n"); }while(ch < 5);
ch = sc.nextInt(); }
switch(ch) }
{
case 1:
int key = sc.nextInt();
s.push(key);
break;
case 2:
System.out.println(s.pop() + " is popped from stack");
break;
case 3:
Stack applications
• If the top of the stack has a higher precedence than the scanned character
pop the stack; Else push the scanned character to stack.
• Repeat these steps until the stack is not empty and top of the stack has
greater precedence over the character.
• If the scanned character is a ‘(‘ (opening parenthesis), push it into the stack.
• If the scanned character is a ‘)’ (closing parenthesis), pop the stack and
output it until a ‘(‘ is encountered, and discard both the parenthesis.
• Print and pop the stack until completely empty.
Suppose we are given string in the infix notation : X * ( Y – Z ).
Evaluation of postfix expression
char stack[SIZE];
int top = -1;
• A queue is a linear data structure that follows first in first out principle
which means the first element inserted in the queue will be removed
first from the queue
• Queue can be implemented using an array (static) or a linked list
(dynamic)
• Basic operations performed on queue are
o Enque
o Deque and
o Front
Queue
• Application of queues
o Serving requests on shared resources(CPU, printer etc.)
o Handling of interrupts
o When data is transferred asynchronously between two processes
• Complexity analysis
o Enqueue O(1)
o Dequeu O(1)
Queue implementation using array
Enque
• Verify queue overflow by checking if (size >= CAPACITY).
• Increment rear size by 1.
• Note, that the increment should not cross array index bounds.
• Which means if suppose queue capacity is 100 and size is 5and rear is at
99 which means front will be at 95. Now when you enqueue a new
element to queue, rear must get updated to 0 instead of 100. Otherwise
array index will go beyond its bounds.
0 1 2 3 4 5 …. 95 96 97 98 99
Front Rear
Queue implementation using array
Enque
Deque
return data;
}
Queue using Stacks
In a tree data structure, nodes which belong to same Parent are called
as SIBLINGS. In simple words, the nodes with same parent are called as
Sibling nodes.
6. Leaf
In a tree data structure, the node which does not have a child is called as LEAF
Node. In simple words, a leaf is a node with no child.
In a tree data structure, the leaf nodes are also called as External Nodes.
External node is also a node with no child. In a tree, leaf node is also called as
'Terminal' node.
7. Internal Nodes
In a tree data structure, the node which has atleast one child is called
as INTERNAL Node. In simple words, an internal node is a node with atleast
one child.
In a tree data structure, nodes other than leaf nodes are called as Internal
Nodes. The root node is also said to be Internal Node if the tree has more
than one node. Internal nodes are also called as 'Non-Terminal' nodes.
8. Degree
In a tree data structure, the total number of children of a node is called
as DEGREE of that Node. In simple words, the Degree of a node is total
number of children it has. The highest degree of a node among all the
nodes in a tree is called as 'Degree of Tree‘.
9. Level
In a tree data structure, the root node is said to be at Level 0 and the children
of root node are at Level 1 and the children of the nodes which are at Level 1
will be at Level 2 and so on... In simple words, in a tree each step from top to
bottom is called as a Level and the Level count starts with '0' and incremented
by one at each level (Step).
10. Height
In a tree data structure, the total number of egdes from leaf node to a particular
node in the longest path is called as HEIGHT of that Node. In a tree, height of
the root node is said to be height of the tree. In a tree, height of all leaf nodes
is '0'.
11. Depth
In a tree data structure, the total number of edges from root node to a
particular node is called as DEPTH of that Node. In a tree, the total number of
edges from root node to a leaf node in the longest path is said to be Depth of
the tree. In simple words, the highest depth of any leaf node in a tree is said to
be depth of that tree. In a tree, depth of the root node is '0'.
12. Path
In a tree data structure, the sequence of Nodes and Edges from one node to
another node is called as PATH between that two Nodes. Length of a Path is
total number of nodes in that path. In below example the path A - B - E - J has
length 4.
13. Sub Tree
In a tree data structure, each child from a node forms a subtree
recursively. Every child node will form a subtree on its parent
node.
Tree Representations
A tree data structure can be represented in many ways.
List Representation
Left Child - Right Sibling Representation
Consider the following tree...
List Representation
• In this representation, we use two types of nodes one for representing the node with
data and another for representing only references. We start with a node with data
from root node in the tree. Then it is linked to an internal node through a reference
node and is linked to any other node directly. This process repeats for all the nodes in
the tree.
• The above tree example can be represented using List representation as follows...
Left Child - Right Sibling Representation
• In this representation, we use list with one type of node which consists of three
fields namely Data field, Left child reference field and Right sibling reference field.
Data field stores the actual value of a node, left reference field stores the address
of the left child and right reference field stores the address of the right sibling
node. Graphical representation of that node is as follows...
Node(String data)
{
this.data = data;
}
class DFS{
static void traversal(Node n)
{
if ( n == null)
return;
System.out.print(n.data + " ");
traversal(n.left);
traversal(n.right);
}
}
Output:
BFS traversal :
ABECDFGH
DFS traversal :
ABCDEFGH
Tree (DFS traversal)
void printPostorder(Node node)
{
if (node == null) void printPreorder(Node node)
{
return;
if (node == null)
return;
printPostorder(node.left); System.out.print(node.key + " ");
printPostorder(node.right);
printPreorder(node.left);
System.out.print(node.key + " ");
printPreorder(node.right);
} }
Output:
void printInorder(Node node)
Preorder traversal of binary tree is
{
12453
if (node == null) Inorder traversal of binary tree is
return; 42513
Postorder traversal of binary tree is
printInorder(node.left);
45231
System.out.print(node.key + " ");
printInorder(node.right);
}
Tree (DFS traversal)
• Pre-order traversal
o Print the data at the root
o Recursively print out all data in the leftmost subtree
o Recursively print out all data in the rightmost subtree
• In-order traversal
o Recursively print out all data in the leftmost subtree
o Print the data at the root
o Recursively print out all data in the rightmost subtree
• Post-order traversal
o Recursively print out all data in the leftmost subtree
o Recursively print out all data in the rightmost subtree
o Print the data at the root
Variants of trees
Binary tree is a tree data structure where a node has at most two
child node
Full binary tree is a tree in which every node has either 0 or 2 child
nodes
Balanced binary tree is a tree in which a node doesn’t have
balancing factor of not more than 1
Binary search tree is a tree which maintains the property of every
child of a given node is placed left if the value of the child node is
lesser than the parent node. A node which has a value greater than a
parent node is placed right of the parent node
Variants of trees
Self balancing tree
A tree which maintains the balancing factor after insertion or
deletion of a new node is called self balancing tree.
AVL tree
A tree which performs a sequence of rotation to maintain balancing
factor is called AVL tree
Binary Search Trees (BST)
• A data structure for efficient searching, inser-tion and deletion
• Binary search tree property
o For every node X
o All the keys in its left
subtree are smaller than
the key value in X
o All the keys in its right
subtree are larger than the
key value in X
Binary Search Trees