You are on page 1of 51

Introduction to data structures

-STACK , QUEUE
Define Data Structure
• Data Structure is a way of collecting and organising
data in such a way that we can perform operations on
these data in an effective way. 
• For example, we have data Student name "Vidhi" and
age 21. Here "Vidhi" is of String data type and 21 is
of integer data type.
• We can organize this data as a record like Student
 record
• Collections of students name can be stored as n record
of information.
• Data Structures are structures programmed
to store ordered data, so that various
operations can be performed on it easily.
• It represents the knowledge of data to be
organized in memory.
• It should be designed and implemented in
such a way that it reduces the complexity and
increases the efficiency.
Basic types of Data Structures
• Primitive Data Structures.
-Integer, Float, Boolean, Char
• Abstract Data Structure:
In computer science, an abstract data type (ADT) is
a mathematical model for data types, where a data type is defined
by its behaviour (semantics) from the point of view of a user of the
data, specifically in terms of possible values, possible operations
on data of this type, and the behaviour of these operations. This
contrasts with data structures, which are concrete representations
of data, and are the point of view of an implementer, not a user.
An ADT may be defined as a "class of objects whose logical
behavior is defined by a set of values and a set of operations“.
Example: Stack, Queue,List,Tree, Graph
The data structures can also be classified on
the basis of the following characteristics:
Characterstic Description
Linear In Linear data structures,the data items are arranged
in a linear sequence. Example: Array
Non-Linear In Non-Linear data structures,the data items are not
in sequence. Example: Tree, Graph
Homogeneous In homogeneous data structures,all the elements are
of same type. Example: Array
Non-Homogeneous In Non-Homogeneous data structure, the elements
may or may not be of the same type.
Example: Structures

Static Static data structures are those whose sizes and


structures associated memory locations are fixed, at
compile time. Example: Array

Dynamic Dynamic structures are those which expands or


shrinks depending upon the program need and its
execution. Also, their associated memory locations
changes. Example: Linked List created using pointers
Space Complexity
• Its the amount of memory space required by the algorithm,
during the course of its execution.
• Space complexity must be taken seriously for multi-user
systems and in situations where limited memory is available.
• An algorithm generally requires space for following
components :
Instruction Space : Its the space required to store the executable
version of the program. This space is fixed, but varies depending
upon the number of lines of code in the program.
Data Space : Its the space required to store all the constants and
Variables value.
Environment Space : Its the space required to store the
environment information needed to resume the suspended
function.
Time Complexity

• Time Complexity is a way to represent the


amount of time needed by the program to
run till its completion.
• We will study this in details in later sections.
Stack and Queue
DATA STRUCTURE
Define Stack and its operation
• A stack is a linear data structure in which all the insertion and
deletion of data or you can say its values are done at one end
only.
• Stack is an ordered list of similar data type. 
• Stack is a LIFO structure. (Last in First out).
• push() function is used to insert new elements into the Stack and
• pop() function is used to delete an element from the stack.
• Both insertion and deletion are allowed at only one end
of Stack called Top.
– Example : consider trays in a cafeteria
• to get the bottom tray out, you must first remove all of the
elements above
Implementing a Stack
• At least three different ways to implement a stack
– array
– Vector
Vectors have a more dynamic structure, often referred to as a heap, which
gives them greater flexibility in how they use memory. While an array uses
a static amount of memory, the memory used by the vector can be
increased or decreased as elements are added or removed from the
vector.
-vectors can typically hold any object - so you can make a class to
hold information about vehicles, and then store the fleet in a vector.
Nice things about vectors, aside from resizing, is that they still
allow access in constant time to individual elements via index, just
like an array.
– linked list
• Which method to use depends on the application
– what advantages and disadvantages does each implementation have?
Implementing Stacks: Array
• Advantages
– best performance
• Disadvantage
– fixed size
• Basic implementation
– initially empty array
– field to record where the next data gets placed into
– if array is full, push() returns false
• otherwise adds it into the correct spot
– if array is empty, pop() returns null
• otherwise removes the next item in the stack
Stack Specification
• Definitions: (provided by the user)
– MAX_ITEMS: Max number of items that might be on
the stack
– ItemType: Data type of the items on the stack
• Operations
– MakeEmpty
– Boolean IsEmpty
– Boolean IsFull
– Push (ItemType newItem)
– Pop (ItemType& item)
Push (ItemType newItem)
• Function: Adds newItem to the top of the
stack.
• Pre conditions: Stack has been initialized
and is not full.
• Post conditions: newItem is at the top of
the stack.
Pop (ItemType& item)
• Function: Removes topItem from stack and
returns it in item.
• Preconditions: Stack has been initialized and is
not empty.
• Post conditions: Top element has been
removed from stack and item is a copy of the
removed element.
A stack can be implemented using array as follows...

Before implementing actual operations, first follow the below


steps to create an empty stack.
Step 1: Include all the header files which are used in the program
and define a constant 'SIZE' with specific value.
Step 2: Declare all the functions used in stack implementation.
Step 3: Create a one dimensional array with fixed size (int
stack[SIZE])
Step 4: Define a integer variable 'top' and initialize with '-1'. (int
top = -1)
Step 5: In main method display menu with list of operations and
make suitable function calls to perform operation selected by the
user on the stack.
push(value) - Inserting value into the stack
Step 1: Check whether stack is FULL. (top == SIZE-1)
Step 2: If it is FULL, then display "Stack is FULL!!! Insertion is not
possible!!!" and terminate the function.
Step 3: If it is NOT FULL, then increment top value by one (top++)
and set stack[top] to value (stack[top] = value).

pop() - Delete a value from the Stack


Step 1: Check whether stack is EMPTY. (top == -1)
Step 2: If it is EMPTY, then display "Stack is EMPTY!!! Deletion is not
possible!!!" and terminate the function.
Step 3: If it is NOT EMPTY, then delete stack[top] and
decrement top value by one (top--).
display() - Displays the elements of a Stack

Step 1: Check whether stack is EMPTY. (top == -1)


Step 2: If it is EMPTY, then display "Stack is EMPTY!!!" and
terminate the function.
Step 3: If it is NOT EMPTY, then define a variable 'i' and
initialize with top. Display stack[i] value and
decrement i value by one (i--).
Step 3: Repeat above step until i value becomes '0'.
Implementation of Stack
Define :
• stack[100],n [Size of the stack],top[Top of
the stack] ,x [Element to push]
Functions defined:
• void push();
• void pop();
• void display();
void push()
{
if(top>=n-1) //Checking top of the Stack
{
printf("\n\t STACK is over flow");
getch();
}
else
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}}
void pop()
{
if (top<=-1) // initially top of the stack is -1
{
printf("\n\t Stack is under flow");
}
else
{
printf("\n\t The popped elements is
%d",stack[top]);
top--; }
}
display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}
}
Stack overflow
• The condition resulting from trying to push
an element onto a full stack.
if(! IsFull())
Push(item);
Stack underflow
• The condition resulting from trying to pop
an empty stack.
if(! IsEmpty())
Pop(item);
The Towers of Hanoi
A Stack-based Application
GIVEN: three poles
a set of discs on the first pole, discs of different sizes, the smallest discs
at the top
GOAL: move all the discs from the left pole to the right one.
CONDITIONS: only one disc may be moved at a time.
A disc can be placed either on an empty pole or on top of a larger disc
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Application of Stack
• Infix to Postfix conversion
[Evaluation of Expressions]
Queue
• Stores a set of elements in a particular
order
• QUEUE principle: FIRST IN FIRST OUT
= FIFO
• It means: the first element inserted is the
first one to be removed
• Example
• The first one in line is the first one to be
served
Queue Applications
• Real life examples
– Waiting in line
– Waiting on hold for tech support
• Applications related to Computer Science
– Threads
– Job scheduling (e.g. Round-Robin algorithm for
CPU allocation)
First In First Out
rear
D rear
C rear C D
B rear B B C
rear front front front
A A front A A B
front
Queue ADT
objects: a finite ordered list with zero or more elements.
methods:
for all queue  Queue, item  element,
max_ queue_ size  positive integer
Queue createQ(max_queue_size) ::=
create an empty queue whose maximum size is
max_queue_size
Boolean isFullQ(queue, max_queue_size) ::=
if(number of elements in queue == max_queue_size)
return TRUE
else return FALSE
Queue Enqueue(queue, item) ::=
if (IsFullQ(queue)) queue_full
else insert item at rear of queue and return queue
Queue ADT (cont’d)
Boolean isEmptyQ(queue) ::=
if (queue ==CreateQ(max_queue_size))
return TRUE
else return FALSE
Element dequeue(queue) ::=
if (IsEmptyQ(queue)) return
else remove and return the item at front of queue.
Array-based Queue Implementation
• As with the array-based stack implementation,
the array is of fixed size
– A queue of maximum N elements
• Slightly more complicated
– Need to maintain track of both front and rear

Implementation 1

Implementation 2
Implementation: Queue using Array
#include<stdio.h>
#include<conio.h>
#define MAX 5

int queue[MAX], front = -1, rear = -1;


void Insert_Element();
void Delete_Element();
void Display_Queue();
void Empty_Queue();
int main()
{
int option;
printf(">>> c program to implement queue operations <<<");
do
{
printf("\n\n 1.Insert an element");
printf("\n 2.Delete an element");
printf("\n 3.Display queue");
printf("\n 4.Empty queue");
printf("\n 5.Exit");
printf("\n Enter your choice: ");
scanf("%d", &option);
switch (option)
{
case 1: Insert_Element();
break;
case 2: Delete_Element();
break;
case 3: Display_Queue();
break;
case 4: Empty_Queue();
break;
case 5: return 0; /*program ends*/
}

} while (option != 5);


}
void Insert_Element()
{
int num;
if (rear <= MAX - 1)
{
if (front == -1) /*when queue is initially empty */
{ front = 0; }

printf("\n Enter the number to be inserted: ");


scanf("%d", &num);
rear = rear + 1;
queue[rear] = num;
}
else
{
printf("\n Queue OverFlow Occured");
}
}
void Delete_Element()
{
int element;

if (front == -1 || front > rear)


{
printf("\n Queue Underflow occured.\n");
return;
}
else
{
element = queue[front];
printf("\n Element deleted from queue is : %d", element);
front = front + 1;
}
}
void Empty_Queue()
{
/*Reset queue or Creates Empty queue*/
front = -1;
rear = -1;
printf("\n New Queue created successfully.");
}
void Display_Queue()
{
int i;
if (front == -1 || front > rear)
printf("\n No elements to display");
else
{
printf("\n The queue elements are:\n ");
for (i = front; i <= rear; i++)
{
printf("\t %d", queue[i]);
}
}
}

You might also like