SlideShare a Scribd company logo
1 of 77
1
Year & Sem – II & III
Section - A,B,C,D
Subject – Data Structures & Algorithms
Unit – I
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
1
VISSION AND MISSION OF INSTITUTE
Vision of the Institute
To become a renowned Centre of higher learning, and work towards academic, professional,
cultural and social enrichment of the lives of individuals and communities.
Mission of the Institute
• To Focus on research and spirit of innovation that will drive academic orientation and
pursuit at JECRC University.
• To Identify, based on informed perception of Indian, regional and global needs, areas of
focus and specialization on which the University can concentrate.
• To Undertake collaborative projects that offer opportunities for long-term interaction
between academia and industry.
• To Develop human potential to its fullest extent so that intellectually capable and
imaginatively gifted leaders can emerge in a range of professions.
1
VISSION AND MISSION OF DEPARTMENT
3
Vision of the Department
To become renowned Centre of excellence in computer science and engineering and
make competent engineers & professionals with high ethical values prepared for
lifelong learning.
Mission of the Department
M1- To impart outcome based education for emerging technologies in the field of
computer science and engineering.
M2 - To provide opportunities for interaction between academia and industry.
M3 - To provide platform for lifelong learning by accepting the change in technologies
M4 - To develop aptitude of fulfilling social responsibilities.
1
COURSE OUTCOME
4
CO1: Apply the concepts of data structure, data type and array data
structure and analyze the algorithms and determine their time complexity.
CO2: Apply various data structure such as stacks, Linked List, queues, trees
and graphs to solve various computing problems using C-programming
language.
CO3: Implement standard algorithms for searching & sorting and identify
when to choose which technique.
CO4: Apply the data structure that efficiently models the information in a
problem.
1
CONTENTS (TO BE COVERED)
❑ Introduction of Data Structures and Algorithms
❑ Stack
❑ Basic Operations (PUSH, POP)
❑ Array Representation of Stack (Static & Dynamic)
❑ Applications of Stack
❑ Tower of Hanoi
❑ Multiple Stack representation using Single Array
1
LECTURE CONTENTS WITH A BLEND OF NPTEL
CONTENTS
❑ Introduction of Data Structures and Algorithms
❑ Stack
❑ Array Representation of Stack (Static & Dynamic)
❑ Applications of Stack
❑ Tower of Hanoi
❑ Multiple Stack representation using Single Array
What is Data Structure?
• A data structure is a way of organizing data in a computer so that it can be used
data effectively.
• For example, we can store a list of items having the same data-type using
the array data structure.
Types of Data Structures
Based on the organizing method of data structure, data structures are divided into two
types.
• Linear Data Structures
• Non - Linear Data Structures
Linear Data Structures Non-Linear Data Structures
• if a data structure organizes the data in sequential
order, then that data structure is called a linear data
structure
• Example
Arrays
List (Linked List)
Stack
Queue
• If a data structure organizes the data in
random order then that data structure is called
as Non-linear data structure.
• Example
Tree
Graph
Dictionaries
Heaps
Tries, Etc.,
Neha Solanki(Assistant Professor, CSE) , JECRC, JAIPUR
DATA
STRUCTURE
LINEAR DATA
STRUCTURE
ARRAY QUEUE STACK
NON LINEAR DATA
STRUCTURE
9
Stack (Last in First Out)
• A stack is called a last-in-first-out (LIFO) collection. This means that
the last thing we added (pushed) is the first thing that gets pulled
(popped) off.
• A stack is a sequence of items that are accessible at only one end
of the sequence
EXAMPLES OF STACK:
11
Basic Operations
⮚ PUSH(Insertion)
⮚ POP (Deletion)
Example
Neha Solanki(Assistant Professor, CSE) , JECRC, JAIPUR
Example of Stack
PUSH Operation
• In a stack, push() is a function used to insert an element into the stack. In a stack,
the new element is always inserted at top position. Push function takes one
integer value as parameter and inserts that value into the stack. We can use the
following steps to push an element on to 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 Operation
• In a stack, pop() is a function used to delete an element from the stack. In a stack,
the element is always deleted from top position. Pop function does not take any
value as parameter. We can use the following steps to pop an element 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 Stack items:
• The steps to display 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'.
Applications
1. Reversing Strings:
• A simple application of stack is reversing strings.
• To reverse a string , the characters of string are pushed
onto the stack one by one as the string is read from left
to right.
• Once all the characters of string are pushed onto stack,
they are popped one by one. Since the character last
pushed in comes out first, subsequent pop operation
results in the reversal of the string.
Example
•To reverse the string ‘REVERSE’ the string is read from left to right and
its characters are pushed .
LIKE: onto a stack.
Applications
2. Checking the validity of an expression containing
nested parenthesis:
• Stacks are also used to check whether a given arithmetic expressions containing
nested parenthesis is properly parenthesized.
• The program for checking the validity of an expression verifies that for each left
parenthesis braces or bracket ,there is a corresponding closing symbol and symbols
are appropriately nested.
For example:
VALID INPUTS INVALID INPUTS
{ } { ( }
( { [ ] } ) ( [ ( ( ) ] )
{ [ ] ( ) } { } [ ] )
[ { ( { } [ ] ( { [ { ) } ( ] } ]
})}]
Applications
3. Evaluating arithmetic expressions
–INFIX notation:
–The general way of writing arithmetic expressions is known as infix
notation. e.g, (a+b)
•PREFIX notation: e.g, +AB
•POSTFIX notation: e.g: AB+
Conversion of Infix to Postfix
1. Scan the Infix expressionfrom left to right for tokens (Operators,
Operands & Parentheses) and perform the steps 2 to 5 for each token in the
Expression.
2. If token is operand, Append it in postfix expression
3. If token is a left parentheses “(“, push it in stack
4. If token is an operator,
– Pop all the operators which are of higher or equal precedence (e.g: -,+,%,/,*)
then the incoming token and append them (in the same order) to the output
Expression.
– After popping out all such operators, push the new token on stack.
Neha Solanki(Assistant Professor, CSE) , JECRC, JAIPUR
Conversion of Infix to Postfix
5. If “)” right parentheses is found,
• Pop all the operators from the Stack and append them to Output String, till you
encounter the Opening Parenthesis “(“.
• Pop the left parenthesis but don’t append it to the output string (Postfix notation
does not have brackets).
6. When all tokens of Infix expression have been scanned. Pop all the elements from
the stack and append them to the Output String.
The Output string is the Corresponding Postfix Notation.
Neha Solanki(Assistant Professor, CSE) , JECRC, JAIPUR
Example: 2+(4-1)*3
2+41-*3
2+41-3*
241-3*+
step1
step2
step3
step4
CURRENT
SYMBOL
ACTION
PERFORMED
STACK STATUS POSTFIX
EXPRESSION
( PUSH ( ( 2
2 2
+ PUSH + (+ 2
( PUSH ( (+( 24
4 24
- PUSH - (+(- 241
1 241-
) POP - (+ 241-
* PUSH * (+* 241-
3 241-3
POP * 241-3*
POP + 241-3*+
)
CONVERSION OF INFIX INTO POSTFIX
{2+(4-1)*3into 241-3*+}
Tower of Hanoi
• The Tower of Hanoi puzzle was invented by the French mathematician Edouard
Lucas in 1883.
• Tower Of Hanoi is a Puzzle involving the usage of Stacks.
• Shifting of discs from source tower to target tower.
• Rules for solving puzzle:
1. One disc can be shifted at once.
2. Only top disc can be shifted.
3. Large disc cannot be placed on smaller disc.
4. Only 3 stacks can be used for solving the puzzle.
•Source Tower having N discs can be solved using (2^N)-1 moves.
Neha Solanki(Assistant Professor, CSE) , JECRC, JAIPUR
Usage of Stacks in Tower of Hanoi
Real life analogy of Stack is Access single disc, Single Access location.
Steps:
1. Move 1 from A to C
2. Move 2 from A to B
3. Move 1 from C to B
4. Move 3 from A to C
5. Move 1 from B to A
6. Move 2 from B to C
7. Move 1 from A to C
Neha Solanki(Assistant Professor, CSE) , JECRC, JAIPUR
Use of Recursion for algorithm
:
Neha Solanki(Assistant Professor, CSE) , JECRC, JAIPUR
Explanation
• The recursion used before
"movedisk" is to move all but the
bottom disk on the initial tower to
an intermediate pole.
• The next line simply moves the
bottom disk to its final resting
place.
• Then on line we move the tower
from the intermediate pole to the
top of the largest disk.
• The base case is detected when
the tower height is 0 and the base
of the tower is moved Use of recursion is again use of stack
Neha Solanki(Assistant Professor, CSE) , JECRC, JAIPUR
Application
▪ Used as Backup rotation Scheme (Backups of Computers
having multiple tapes/media)
✔A backup rotation scheme is a system for managing your
backup storage media (tapes/DVDs/HDDs).
▪ Used by neuropsychologists trying to evaluate frontal lobe
deficits.
▪ Used to Solve mathematical problems related to Hamilton
Cycle.
Neha Solanki(Assistant Professor, CSE) , JECRC, JAIPUR
Representation of Stack
• Stack can be represented in two ways
1. Using array
2. Using linked lists
Both the representations are having their own advantages and disadvantages. So
to select the representation of stack is application dependent.
Stack representation using static array
• Stack data structure can be implemented using a one-dimensional array.
• Size of array is fixed.
• Basic steps to create an empty stack.
1. Include all the header files which are used in the program and define a
constant 'SIZE' with specific value.
2. Declare all the functions used in stack implementation.
3. Create a one dimensional array with fixed size.
4. Define a integer variable 'top' and initialize with '-1'. (int top = -1)
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.
• #include<stdio.h>
• #include<conio.h>
• #define SIZE 10
• int stack[SIZE], top=-1;
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).
void push(int value)
{
If(top==SIZE-1)
printf(“stack is full!!! Insertion is not possible”);
else
{
top++;
stack[top]=value;
printf(“successfully inserted”);
}
}
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--).
void pop()
{
if(top==-1)
printf(“stack is empty!! Deletion not possible”);
else{
printf(“deleted: %d”,stack[top]);
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'.
void display()
{
if(top == -1)
printf("nStack is Empty!!!");
else{
int i;
printf("nStack elements are:n");
for(i=top; i>=0; i--)
printf("%dn",stack[i]);
}
}
void main()
{
int value, choice;
clrscr();
while(1){
printf("nn***** MENU *****n");
printf("1. Pushn2. Popn3.
Displayn4. Exit");
printf("nEnter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be
insert: ");
scanf("%d",&value); push(value);
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("nWrong selection!!!
Try again!!!");
} } }
42
• In the implementation of stack using static array, size is always predefined or
fixed.
• Once stack is created its size cannot be changed hence a condition called “stack
full”
arises.
• To overcome this problem we will use dynamic array/ growable stack.
• So a dynamic array can change its capacity.
• Growable stack is the concept of allocating more memory such that stack full
condition does not arises easily.
• A growable array base stack can be implemented by allocating new memory
larger than previous stack memory and copying elements from old stack to new
stack.
• And then at last the name of the new stack as the name given to the previous
stack.
Strategy for growable stack
• There are two strategies:
1. Tight Strategy : Add a constant amount to the old stack (N+c)
2. Growth Strategy : Double the size of old stack (2N)
• Following steps should be done
1. Allocate new space
2. Copy data to new space
3. Free old space
Implement Stack Operations using Dynamic
Memory Allocation
Problem Solution
1. Use malloc function to allocate memory.
2. Define separate functions for the operations like push, pop and display.
3. Use switch statement to access these functions.
Program
#include<stdio.h>
#include<stdlib.h>
struct stack
{
int * a;
int top;
int maxSize;
};
void initstack(struct stack * p, int maxSize);
void push(struct stack * p, int item);
void display(struct stack p);
int pop(struct stack * p);
void printMenu();
int main()
{
struct stack p;
int data,ch, data1, m;
printf("Enter the maximum size of the stackn");
scanf("%d",&m);
initstack(&p,m);
do
{
printMenu();
printf("Enter your choicen");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter the element to be pushedn");
scanf("%d",&data);
push(&p, data);
break;
case 2:
data1 = pop(&p);
if(data1 != -1000)
printf("The popped element is %dn",data1);
break;
case 3: printf("The contents of the stack are");
display(p);
printf("n");
break;
default:
return 0;
}
}
while(1);
return 0;
}
void printMenu()
{
printf("Choice 1 : Pushn");
printf("Choice 2 : Popn");
printf("Choice 3 : Displayn");
printf("Any other choice : Exitn");
}
void initstack(struct stack * p, int maxSize)
{
p->top=-1;
p->maxSize=maxSize;
}
void push(struct stack * p, int item)
{
if (p->top == p->maxSize-1)
{
printf("Stack is fulln");
return;
}
p->a = (int *)malloc(sizeof(int));
p->top++;
p->a[p->top] =item;
p->maxSize--;
}
void display(struct stack p)
{
struct stack *p1;
p1=&p;
int a[30],n=0,i;
for (i = p1->top ; i >= 0; i--)
{
printf("n%d", p1->a[i]);
}
}
int pop(struct stack * p)
{
int num;
if(p->top == -1)
{
printf("Stack is emptyn");
return -1000;
}
num = p->a[p->top];
p->top--;
return num;
}
Stack Using Linked List
53
Linked List in Data Structure
• A linked list is a linear data structure, in which the elements are not
stored at contiguous memory locations. The elements in a linked list
are linked using pointers as shown in the below image:
A linked list is represented by a pointer to the first node of the linked list. The first node is called the
head. If the linked list is empty, then the value of the head is NULL.
Each node in a list consists of at least two parts:
1) data
2) Pointer (Or Reference) to the next node
Why Linked List?
• Arrays can be used to store linear data of similar types, but
arrays have the following limitations.
1) The size of the arrays is fixed: So we must know the upper
limit on the number of elements in advance. Also, generally, the
allocated memory is equal to the upper limit irrespective of the
usage.
2) Inserting a new element in an array of elements is expensive
because the room has to be created for the new elements and
to create room existing elements have to be shifted.
For example, in a system, if we maintain a sorted list of IDs in
an array id[].
• id[] = [1000, 1010, 1050, 2000, 2040].
• And if we want to insert a new ID 1005, then to maintain the
sorted order, we have to move all the elements after 1000
(excluding 1000).
Deletion is also expensive with arrays until unless some
special techniques are used. For example, to delete 1010 in
id[], everything after 1010 has to be moved.
Advantages over arrays
• They are a dynamic in nature which allocates the memory when
required.
• Insertion and deletion operations can be easily implemented.
• Stacks and queues can be easily executed.
• Linked List reduces the access time.
Disadvantages of Linked Lists
• The memory is wasted as pointers require extra memory for storage.
• No element can be accessed randomly; it has to access each node
sequentially.
• Reverse Traversing is difficult in linked list.
• Random access is not allowed. We have to access elements
sequentially starting from the first node. So we cannot do binary
search with linked lists efficiently with its default implementation.
• Extra memory space for a pointer is required with each element of the
list.
• Not cache friendly. Since array elements are contiguous locations,
there is locality of reference which is not there in case of linked
lists.
Applications of Linked Lists
• Linked lists are used to implement stacks, queues, graphs, etc.
• Linked lists let you insert elements at the beginning and end of the list.
• In Linked Lists we don't need to know the size in advance.
Types of Linked Lists:
There are 3 different implementations of Linked List available, they are:
• Singly Linked List
• Doubly Linked List
• Circular Linked List
Singly Linked List
Singly linked lists contain nodes which have a data part as well as
an address part i.e. next, which points to the next node in the
sequence of nodes.
The operations we can perform on singly linked lists
are insertion, deletion and traversal.
Doubly Linked List
In a doubly linked list, each node contains a data part and two
addresses, one for the previous node and one for the next node.
Circular Linked List
In circular linked list the last node of the list holds the address of
the first node hence forming a circular chain.
ARRAY LINKED LIST
Array is a collection of elements of similar data type. Linked List is an ordered collection of elements of same type, which are
connected to each other using pointers.
Array supports Random Access, which means elements can be
accessed directly using their index, like arr[0] for 1st element, arr[6] for 7th
element etc.
Hence, accessing elements in an array is fast with a constant time
complexity of O(1).
Linked List supports Sequential Access, which means to access any
element/node in a linked list, we have to sequentially traverse the
complete linked list, upto that element.
To access nth element of a linked list, time complexity is O(n).
In an array, elements are stored in contiguous memory location or
consecutive manner in the memory.
In a linked list, new elements can be stored anywhere in the memory.
Address of the memory location allocated to the new element is stored in
the previous node of linked list, hence formaing a link between the two
nodes/elements.
In array, Insertion and Deletion operation takes more time, as the
memory locations are consecutive and fixed.
In case of linked list, a new element is stored at the first free and available
memory location, with only a single overhead step of storing the address
of memory location in the previous node of linked list.
Insertion and Deletion operations are fast in linked list.
Memory is allocated as soon as the array is declared, at compile time.
It's also known as Static Memory Allocation.
Memory is allocated at runtime, as and when a new node is added. It's
also known as Dynamic Memory Allocation.
In array, each element is independent and can be accessed using it's
index value.
In case of a linked list, each node/element points to the next, previous, or
maybe both nodes.
Array can single dimensional, two dimensional or multidimensional Linked list can be Linear(Singly), Doubly or Circular linked list.
Size of the array must be specified at time of array decalaration. Size of a Linked list is variable. It grows at runtime, as more nodes are
added to it.
Array gets memory allocated in the Stack section. Whereas, linked list gets memory allocated in Heap section.
77
Neha Solanki(Assistant Professor, CSE) , JECRC, JAIPUR

More Related Content

Similar to Unit I.pptx

Stack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTStack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTSoumen Santra
 
Unit 1_Stack and Queue using Linked Organization.pdf
Unit 1_Stack and Queue using Linked Organization.pdfUnit 1_Stack and Queue using Linked Organization.pdf
Unit 1_Stack and Queue using Linked Organization.pdfKanchanPatil34
 
Stack in Data Structure
Stack in Data StructureStack in Data Structure
Stack in Data StructureUshaP15
 
stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for publiciqbalphy1
 
358 33 powerpoint-slides_9-stacks-queues_chapter-9
358 33 powerpoint-slides_9-stacks-queues_chapter-9358 33 powerpoint-slides_9-stacks-queues_chapter-9
358 33 powerpoint-slides_9-stacks-queues_chapter-9sumitbardhan
 
DS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxDS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxprakashvs7
 
Ds stack & queue
Ds   stack & queueDs   stack & queue
Ds stack & queueSunipa Bera
 
My lecture stack_queue_operation
My lecture stack_queue_operationMy lecture stack_queue_operation
My lecture stack_queue_operationSenthil Kumar
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURESUsha Mahalingam
 
Stack and Queue.pptx
Stack and Queue.pptxStack and Queue.pptx
Stack and Queue.pptxDdushb
 
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptxSTACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptxKALPANAC20
 
stack 1.pdf
stack 1.pdfstack 1.pdf
stack 1.pdfhafsa40
 
ADS_Lec1_Linear_lists_Stacks
ADS_Lec1_Linear_lists_StacksADS_Lec1_Linear_lists_Stacks
ADS_Lec1_Linear_lists_StacksHemanth Kumar
 

Similar to Unit I.pptx (20)

Stack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTStack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADT
 
Unit 1_Stack and Queue using Linked Organization.pdf
Unit 1_Stack and Queue using Linked Organization.pdfUnit 1_Stack and Queue using Linked Organization.pdf
Unit 1_Stack and Queue using Linked Organization.pdf
 
Stack a Data Structure
Stack a Data StructureStack a Data Structure
Stack a Data Structure
 
Stack in Data Structure
Stack in Data StructureStack in Data Structure
Stack in Data Structure
 
stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for public
 
358 33 powerpoint-slides_9-stacks-queues_chapter-9
358 33 powerpoint-slides_9-stacks-queues_chapter-9358 33 powerpoint-slides_9-stacks-queues_chapter-9
358 33 powerpoint-slides_9-stacks-queues_chapter-9
 
DS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxDS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptx
 
Ds stack & queue
Ds   stack & queueDs   stack & queue
Ds stack & queue
 
Stacks
StacksStacks
Stacks
 
My lecture stack_queue_operation
My lecture stack_queue_operationMy lecture stack_queue_operation
My lecture stack_queue_operation
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURES
 
DS UNIT1_STACKS.pptx
DS UNIT1_STACKS.pptxDS UNIT1_STACKS.pptx
DS UNIT1_STACKS.pptx
 
Stack and Queue.pptx
Stack and Queue.pptxStack and Queue.pptx
Stack and Queue.pptx
 
Stack in Sata Structure
Stack in Sata StructureStack in Sata Structure
Stack in Sata Structure
 
DS MOD2 (1) (1).pptx
DS MOD2 (1) (1).pptxDS MOD2 (1) (1).pptx
DS MOD2 (1) (1).pptx
 
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptxSTACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
 
stack.pptx
stack.pptxstack.pptx
stack.pptx
 
stack 1.pdf
stack 1.pdfstack 1.pdf
stack 1.pdf
 
ADS_Lec1_Linear_lists_Stacks
ADS_Lec1_Linear_lists_StacksADS_Lec1_Linear_lists_Stacks
ADS_Lec1_Linear_lists_Stacks
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 

Recently uploaded

GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxnada99848
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 

Recently uploaded (20)

GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptx
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 

Unit I.pptx

  • 1. 1 Year & Sem – II & III Section - A,B,C,D Subject – Data Structures & Algorithms Unit – I JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
  • 2. 1 VISSION AND MISSION OF INSTITUTE Vision of the Institute To become a renowned Centre of higher learning, and work towards academic, professional, cultural and social enrichment of the lives of individuals and communities. Mission of the Institute • To Focus on research and spirit of innovation that will drive academic orientation and pursuit at JECRC University. • To Identify, based on informed perception of Indian, regional and global needs, areas of focus and specialization on which the University can concentrate. • To Undertake collaborative projects that offer opportunities for long-term interaction between academia and industry. • To Develop human potential to its fullest extent so that intellectually capable and imaginatively gifted leaders can emerge in a range of professions.
  • 3. 1 VISSION AND MISSION OF DEPARTMENT 3 Vision of the Department To become renowned Centre of excellence in computer science and engineering and make competent engineers & professionals with high ethical values prepared for lifelong learning. Mission of the Department M1- To impart outcome based education for emerging technologies in the field of computer science and engineering. M2 - To provide opportunities for interaction between academia and industry. M3 - To provide platform for lifelong learning by accepting the change in technologies M4 - To develop aptitude of fulfilling social responsibilities.
  • 4. 1 COURSE OUTCOME 4 CO1: Apply the concepts of data structure, data type and array data structure and analyze the algorithms and determine their time complexity. CO2: Apply various data structure such as stacks, Linked List, queues, trees and graphs to solve various computing problems using C-programming language. CO3: Implement standard algorithms for searching & sorting and identify when to choose which technique. CO4: Apply the data structure that efficiently models the information in a problem.
  • 5. 1 CONTENTS (TO BE COVERED) ❑ Introduction of Data Structures and Algorithms ❑ Stack ❑ Basic Operations (PUSH, POP) ❑ Array Representation of Stack (Static & Dynamic) ❑ Applications of Stack ❑ Tower of Hanoi ❑ Multiple Stack representation using Single Array
  • 6. 1 LECTURE CONTENTS WITH A BLEND OF NPTEL CONTENTS ❑ Introduction of Data Structures and Algorithms ❑ Stack ❑ Array Representation of Stack (Static & Dynamic) ❑ Applications of Stack ❑ Tower of Hanoi ❑ Multiple Stack representation using Single Array
  • 7. What is Data Structure? • A data structure is a way of organizing data in a computer so that it can be used data effectively. • For example, we can store a list of items having the same data-type using the array data structure.
  • 8. Types of Data Structures Based on the organizing method of data structure, data structures are divided into two types. • Linear Data Structures • Non - Linear Data Structures Linear Data Structures Non-Linear Data Structures • if a data structure organizes the data in sequential order, then that data structure is called a linear data structure • Example Arrays List (Linked List) Stack Queue • If a data structure organizes the data in random order then that data structure is called as Non-linear data structure. • Example Tree Graph Dictionaries Heaps Tries, Etc., Neha Solanki(Assistant Professor, CSE) , JECRC, JAIPUR
  • 9. DATA STRUCTURE LINEAR DATA STRUCTURE ARRAY QUEUE STACK NON LINEAR DATA STRUCTURE 9
  • 10. Stack (Last in First Out) • A stack is called a last-in-first-out (LIFO) collection. This means that the last thing we added (pushed) is the first thing that gets pulled (popped) off. • A stack is a sequence of items that are accessible at only one end of the sequence
  • 15. PUSH Operation • In a stack, push() is a function used to insert an element into the stack. In a stack, the new element is always inserted at top position. Push function takes one integer value as parameter and inserts that value into the stack. We can use the following steps to push an element on to 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).
  • 16. POP Operation • In a stack, pop() is a function used to delete an element from the stack. In a stack, the element is always deleted from top position. Pop function does not take any value as parameter. We can use the following steps to pop an element 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--).
  • 17. Display Stack items: • The steps to display 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'.
  • 18. Applications 1. Reversing Strings: • A simple application of stack is reversing strings. • To reverse a string , the characters of string are pushed onto the stack one by one as the string is read from left to right. • Once all the characters of string are pushed onto stack, they are popped one by one. Since the character last pushed in comes out first, subsequent pop operation results in the reversal of the string.
  • 19. Example •To reverse the string ‘REVERSE’ the string is read from left to right and its characters are pushed . LIKE: onto a stack.
  • 20. Applications 2. Checking the validity of an expression containing nested parenthesis: • Stacks are also used to check whether a given arithmetic expressions containing nested parenthesis is properly parenthesized. • The program for checking the validity of an expression verifies that for each left parenthesis braces or bracket ,there is a corresponding closing symbol and symbols are appropriately nested.
  • 21. For example: VALID INPUTS INVALID INPUTS { } { ( } ( { [ ] } ) ( [ ( ( ) ] ) { [ ] ( ) } { } [ ] ) [ { ( { } [ ] ( { [ { ) } ( ] } ] })}]
  • 22. Applications 3. Evaluating arithmetic expressions –INFIX notation: –The general way of writing arithmetic expressions is known as infix notation. e.g, (a+b) •PREFIX notation: e.g, +AB •POSTFIX notation: e.g: AB+
  • 23. Conversion of Infix to Postfix 1. Scan the Infix expressionfrom left to right for tokens (Operators, Operands & Parentheses) and perform the steps 2 to 5 for each token in the Expression. 2. If token is operand, Append it in postfix expression 3. If token is a left parentheses “(“, push it in stack 4. If token is an operator, – Pop all the operators which are of higher or equal precedence (e.g: -,+,%,/,*) then the incoming token and append them (in the same order) to the output Expression. – After popping out all such operators, push the new token on stack. Neha Solanki(Assistant Professor, CSE) , JECRC, JAIPUR
  • 24. Conversion of Infix to Postfix 5. If “)” right parentheses is found, • Pop all the operators from the Stack and append them to Output String, till you encounter the Opening Parenthesis “(“. • Pop the left parenthesis but don’t append it to the output string (Postfix notation does not have brackets). 6. When all tokens of Infix expression have been scanned. Pop all the elements from the stack and append them to the Output String. The Output string is the Corresponding Postfix Notation. Neha Solanki(Assistant Professor, CSE) , JECRC, JAIPUR
  • 26. CURRENT SYMBOL ACTION PERFORMED STACK STATUS POSTFIX EXPRESSION ( PUSH ( ( 2 2 2 + PUSH + (+ 2 ( PUSH ( (+( 24 4 24 - PUSH - (+(- 241 1 241- ) POP - (+ 241- * PUSH * (+* 241- 3 241-3 POP * 241-3* POP + 241-3*+ ) CONVERSION OF INFIX INTO POSTFIX {2+(4-1)*3into 241-3*+}
  • 27. Tower of Hanoi • The Tower of Hanoi puzzle was invented by the French mathematician Edouard Lucas in 1883. • Tower Of Hanoi is a Puzzle involving the usage of Stacks. • Shifting of discs from source tower to target tower. • Rules for solving puzzle: 1. One disc can be shifted at once. 2. Only top disc can be shifted. 3. Large disc cannot be placed on smaller disc. 4. Only 3 stacks can be used for solving the puzzle. •Source Tower having N discs can be solved using (2^N)-1 moves. Neha Solanki(Assistant Professor, CSE) , JECRC, JAIPUR
  • 28. Usage of Stacks in Tower of Hanoi Real life analogy of Stack is Access single disc, Single Access location. Steps: 1. Move 1 from A to C 2. Move 2 from A to B 3. Move 1 from C to B 4. Move 3 from A to C 5. Move 1 from B to A 6. Move 2 from B to C 7. Move 1 from A to C Neha Solanki(Assistant Professor, CSE) , JECRC, JAIPUR
  • 29. Use of Recursion for algorithm : Neha Solanki(Assistant Professor, CSE) , JECRC, JAIPUR
  • 30. Explanation • The recursion used before "movedisk" is to move all but the bottom disk on the initial tower to an intermediate pole. • The next line simply moves the bottom disk to its final resting place. • Then on line we move the tower from the intermediate pole to the top of the largest disk. • The base case is detected when the tower height is 0 and the base of the tower is moved Use of recursion is again use of stack Neha Solanki(Assistant Professor, CSE) , JECRC, JAIPUR
  • 31. Application ▪ Used as Backup rotation Scheme (Backups of Computers having multiple tapes/media) ✔A backup rotation scheme is a system for managing your backup storage media (tapes/DVDs/HDDs). ▪ Used by neuropsychologists trying to evaluate frontal lobe deficits. ▪ Used to Solve mathematical problems related to Hamilton Cycle. Neha Solanki(Assistant Professor, CSE) , JECRC, JAIPUR
  • 32. Representation of Stack • Stack can be represented in two ways 1. Using array 2. Using linked lists Both the representations are having their own advantages and disadvantages. So to select the representation of stack is application dependent.
  • 33. Stack representation using static array • Stack data structure can be implemented using a one-dimensional array. • Size of array is fixed.
  • 34. • Basic steps to create an empty stack. 1. Include all the header files which are used in the program and define a constant 'SIZE' with specific value. 2. Declare all the functions used in stack implementation. 3. Create a one dimensional array with fixed size. 4. Define a integer variable 'top' and initialize with '-1'. (int top = -1) 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.
  • 35. • #include<stdio.h> • #include<conio.h> • #define SIZE 10 • int stack[SIZE], top=-1;
  • 36. 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).
  • 37. void push(int value) { If(top==SIZE-1) printf(“stack is full!!! Insertion is not possible”); else { top++; stack[top]=value; printf(“successfully inserted”); } }
  • 38. 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--).
  • 39. void pop() { if(top==-1) printf(“stack is empty!! Deletion not possible”); else{ printf(“deleted: %d”,stack[top]); top--; } }
  • 40. 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'.
  • 41. void display() { if(top == -1) printf("nStack is Empty!!!"); else{ int i; printf("nStack elements are:n"); for(i=top; i>=0; i--) printf("%dn",stack[i]); } }
  • 42. void main() { int value, choice; clrscr(); while(1){ printf("nn***** MENU *****n"); printf("1. Pushn2. Popn3. Displayn4. Exit"); printf("nEnter your choice: "); scanf("%d",&choice); switch(choice){ case 1: printf("Enter the value to be insert: "); scanf("%d",&value); push(value); break; case 2: pop(); break; case 3: display(); break; case 4: exit(0); default: printf("nWrong selection!!! Try again!!!"); } } } 42
  • 43. • In the implementation of stack using static array, size is always predefined or fixed. • Once stack is created its size cannot be changed hence a condition called “stack full” arises. • To overcome this problem we will use dynamic array/ growable stack. • So a dynamic array can change its capacity.
  • 44. • Growable stack is the concept of allocating more memory such that stack full condition does not arises easily. • A growable array base stack can be implemented by allocating new memory larger than previous stack memory and copying elements from old stack to new stack. • And then at last the name of the new stack as the name given to the previous stack.
  • 45. Strategy for growable stack • There are two strategies: 1. Tight Strategy : Add a constant amount to the old stack (N+c) 2. Growth Strategy : Double the size of old stack (2N)
  • 46.
  • 47. • Following steps should be done 1. Allocate new space 2. Copy data to new space 3. Free old space
  • 48. Implement Stack Operations using Dynamic Memory Allocation Problem Solution 1. Use malloc function to allocate memory. 2. Define separate functions for the operations like push, pop and display. 3. Use switch statement to access these functions.
  • 49. Program #include<stdio.h> #include<stdlib.h> struct stack { int * a; int top; int maxSize; }; void initstack(struct stack * p, int maxSize); void push(struct stack * p, int item); void display(struct stack p); int pop(struct stack * p); void printMenu(); int main() { struct stack p; int data,ch, data1, m;
  • 50. printf("Enter the maximum size of the stackn"); scanf("%d",&m); initstack(&p,m); do { printMenu(); printf("Enter your choicen"); scanf("%d",&ch); switch(ch) { case 1: printf("Enter the element to be pushedn"); scanf("%d",&data); push(&p, data); break; case 2: data1 = pop(&p); if(data1 != -1000) printf("The popped element is %dn",data1); break;
  • 51. case 3: printf("The contents of the stack are"); display(p); printf("n"); break; default: return 0; } } while(1); return 0; } void printMenu() { printf("Choice 1 : Pushn"); printf("Choice 2 : Popn"); printf("Choice 3 : Displayn"); printf("Any other choice : Exitn"); } void initstack(struct stack * p, int maxSize) { p->top=-1; p->maxSize=maxSize; } void push(struct stack * p, int item) { if (p->top == p->maxSize-1) { printf("Stack is fulln"); return; } p->a = (int *)malloc(sizeof(int)); p->top++; p->a[p->top] =item; p->maxSize--; } void display(struct stack p) { struct stack *p1; p1=&p; int a[30],n=0,i; for (i = p1->top ; i >= 0; i--) { printf("n%d", p1->a[i]); } }
  • 52. int pop(struct stack * p) { int num; if(p->top == -1) { printf("Stack is emptyn"); return -1000; } num = p->a[p->top]; p->top--; return num; }
  • 54. Linked List in Data Structure • A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image: A linked list is represented by a pointer to the first node of the linked list. The first node is called the head. If the linked list is empty, then the value of the head is NULL. Each node in a list consists of at least two parts: 1) data 2) Pointer (Or Reference) to the next node
  • 55. Why Linked List? • Arrays can be used to store linear data of similar types, but arrays have the following limitations. 1) The size of the arrays is fixed: So we must know the upper limit on the number of elements in advance. Also, generally, the allocated memory is equal to the upper limit irrespective of the usage. 2) Inserting a new element in an array of elements is expensive because the room has to be created for the new elements and to create room existing elements have to be shifted.
  • 56. For example, in a system, if we maintain a sorted list of IDs in an array id[]. • id[] = [1000, 1010, 1050, 2000, 2040]. • And if we want to insert a new ID 1005, then to maintain the sorted order, we have to move all the elements after 1000 (excluding 1000). Deletion is also expensive with arrays until unless some special techniques are used. For example, to delete 1010 in id[], everything after 1010 has to be moved.
  • 57. Advantages over arrays • They are a dynamic in nature which allocates the memory when required. • Insertion and deletion operations can be easily implemented. • Stacks and queues can be easily executed. • Linked List reduces the access time. Disadvantages of Linked Lists • The memory is wasted as pointers require extra memory for storage. • No element can be accessed randomly; it has to access each node sequentially. • Reverse Traversing is difficult in linked list. • Random access is not allowed. We have to access elements sequentially starting from the first node. So we cannot do binary search with linked lists efficiently with its default implementation. • Extra memory space for a pointer is required with each element of the list. • Not cache friendly. Since array elements are contiguous locations, there is locality of reference which is not there in case of linked lists.
  • 58. Applications of Linked Lists • Linked lists are used to implement stacks, queues, graphs, etc. • Linked lists let you insert elements at the beginning and end of the list. • In Linked Lists we don't need to know the size in advance.
  • 59. Types of Linked Lists: There are 3 different implementations of Linked List available, they are: • Singly Linked List • Doubly Linked List • Circular Linked List
  • 60. Singly Linked List Singly linked lists contain nodes which have a data part as well as an address part i.e. next, which points to the next node in the sequence of nodes. The operations we can perform on singly linked lists are insertion, deletion and traversal.
  • 61. Doubly Linked List In a doubly linked list, each node contains a data part and two addresses, one for the previous node and one for the next node.
  • 62. Circular Linked List In circular linked list the last node of the list holds the address of the first node hence forming a circular chain.
  • 63. ARRAY LINKED LIST Array is a collection of elements of similar data type. Linked List is an ordered collection of elements of same type, which are connected to each other using pointers. Array supports Random Access, which means elements can be accessed directly using their index, like arr[0] for 1st element, arr[6] for 7th element etc. Hence, accessing elements in an array is fast with a constant time complexity of O(1). Linked List supports Sequential Access, which means to access any element/node in a linked list, we have to sequentially traverse the complete linked list, upto that element. To access nth element of a linked list, time complexity is O(n). In an array, elements are stored in contiguous memory location or consecutive manner in the memory. In a linked list, new elements can be stored anywhere in the memory. Address of the memory location allocated to the new element is stored in the previous node of linked list, hence formaing a link between the two nodes/elements. In array, Insertion and Deletion operation takes more time, as the memory locations are consecutive and fixed. In case of linked list, a new element is stored at the first free and available memory location, with only a single overhead step of storing the address of memory location in the previous node of linked list. Insertion and Deletion operations are fast in linked list. Memory is allocated as soon as the array is declared, at compile time. It's also known as Static Memory Allocation. Memory is allocated at runtime, as and when a new node is added. It's also known as Dynamic Memory Allocation. In array, each element is independent and can be accessed using it's index value. In case of a linked list, each node/element points to the next, previous, or maybe both nodes. Array can single dimensional, two dimensional or multidimensional Linked list can be Linear(Singly), Doubly or Circular linked list. Size of the array must be specified at time of array decalaration. Size of a Linked list is variable. It grows at runtime, as more nodes are added to it. Array gets memory allocated in the Stack section. Whereas, linked list gets memory allocated in Heap section.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77. 77 Neha Solanki(Assistant Professor, CSE) , JECRC, JAIPUR