SlideShare a Scribd company logo
1 of 5
Download to read offline
http://www.tutorialspoint.com/data_structures_algorithms/stack_algorithm.htm Copyright © tutorialspoint.com
DATA STRUCTURE - STACKDATA STRUCTURE - STACK
A stack is an abstract data type ADT, commonly used in most programming languages. It is named
stack as it behaves like a real-world stack, for example − deck of cards or pile of plates etc.
A real-world stack allows operations at one end only. For example, we can place or remove a card
or plate from top of the stack only. Likewise, Stack ADT allows all data operations at one end only.
At any given time, We can only access the top element of a stack.
This feature makes it LIFO data structure. LIFO stands for Last-in-first-out. Here, the element which
is placed insertedoradded last, is accessed first. In stack terminology, insertion operation is called
PUSH operation and removal operation is called POP operation.
Stack Representation
Below given diagram tries to depict a stack and its operations −
A stack can be implemented by means of Array, Structure, Pointer and Linked-List. Stack can
either be a fixed size one or it may have a sense of dynamic resizing. Here, we are going to
implement stack using arrays which makes it a fixed size stack implementation.
Basic Operations
Stack operations may involve initializing the stack, using it and then de-initializing it. Apart from
these basic stuffs, a stack is used for the following two primary operations −
push − pushing storing an element on the stack.
pop − removing accessing an element from the stack.
When data is PUSHed onto stack.
To use a stack efficiently we need to check status of stack as well. For the same purpose, the
following functionality is added to stacks −
peek − get the top data element of the stack, without removing it.
isFull − check if stack is full.
isEmpty − check if stack is empty.
At all times, we maintain a pointer to the last PUSHed data on the stack. As this pointer always
represents the top of the stack, hence named top. The top pointer provides top value of the stack
without actually removing it.
First we should learn about procedures to support stack functions −
peek
Algorithm of peek function −
begin procedure peek
return stack[top]
end procedure
Implementation of peek function in C programming language −
int peek() {
return stack[top];
}
isfull
Algorithm of isfull function −
begin procedure isfull
if top equals to MAXSIZE
return true
else
return false
endif
end procedure
Implementation of isfull function in C programming language −
bool isfull() {
if(top == MAXSIZE)
return true;
else
return false;
}
isempty
Algorithm of isempty function −
begin procedure isempty
if top less than 1
return true
else
return false
endif
end procedure
Implementation of isempty function in C programming language is slightly different. We initialize
top at -1, as index in array starts from 0. So we check if top is below zero or -1 to determine if stack
is empty. Here's the code −
bool isempty() {
if(top == -1)
return true;
else
return false;
}
PUSH Operation
The process of putting a new data element onto stack is known as PUSH Operation. Push operation
involves series of steps −
Step 1 − Check if stack is full.
Step 2 − If stack is full, produce error and exit.
Step 3 − If stack is not full, increment top to point next empty space.
Step 4 − Add data element to the stack location, where top is pointing.
Step 5 − return success.
if linked-list is used to implement stack, then in step 3, we need to allocate space dynamically.
Algorithm for PUSH operation
A simple algorithm for Push operation can be derived as follows −
begin procedure push: stack, data
if stack is full
return null
endif
top ← top + 1
stack[top] ← data
end procedure
Implementation of this algorithm in C, is very easy. See the below code −
void push(int data) {
if(!isFull()) {
top = top + 1;
stack[top] = data;
}else {
printf("Could not insert data, Stack is full.n");
}
}
Pop Operation
Accessing the content while removing it from stack, is known as pop operation. In array
implementation of pop operation, data element is not actually removed, instead top is
decremented to a lower position in stack to point to next value. But in linked-list implementation,
pop actually removes data element and deallocates memory space.
A POP operation may involve the following steps −
Step 1 − Check if stack is empty.
Step 2 − If stack is empty, produce error and exit.
Step 3 − If stack is not empty, access the data element at which top is pointing.
Step 4 − Decrease the value of top by 1.
Step 5 − return success.
Algorithm for POP operation
A simple algorithm for Pop operation can be derived as follows −
begin procedure pop: stack
if stack is empty
return null
endif
data ← stack[top]
top ← top - 1
return data
end procedure
Implementation of this algorithm in C, is shown below −
int pop(int data) {
if(!isempty()) {
data = stack[top];
top = top - 1;
return data;
}else {
printf("Could not retrieve data, Stack is empty.n");
}
}
For a complete stack program in C programming language, please click here.
Loading [MathJax]/jax/output/HTML-CSS/jax.js

More Related Content

What's hot

Stack organization
Stack organizationStack organization
Stack organizationchauhankapil
 
Stack linked list
Stack linked listStack linked list
Stack linked listbhargav0077
 
computer notes - Data Structures - 6
computer notes - Data Structures - 6computer notes - Data Structures - 6
computer notes - Data Structures - 6ecomputernotes
 
Stacks in DATA STRUCTURE
Stacks in DATA STRUCTUREStacks in DATA STRUCTURE
Stacks in DATA STRUCTUREMandeep Singh
 
Algorithm and Data Structure - Queue
Algorithm and Data Structure - QueueAlgorithm and Data Structure - Queue
Algorithm and Data Structure - QueueAndiNurkholis1
 
Mapreduce: Theory and implementation
Mapreduce: Theory and implementationMapreduce: Theory and implementation
Mapreduce: Theory and implementationSri Prasanna
 
Algorithm and Data Structure - Stack
Algorithm and Data Structure - StackAlgorithm and Data Structure - Stack
Algorithm and Data Structure - StackAndiNurkholis1
 
Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queuestech4us
 
What is Stack? Application of Stack
What is Stack? Application of StackWhat is Stack? Application of Stack
What is Stack? Application of StackShahzeb Amjad
 
R Programming: Introduction to Matrices
R Programming: Introduction to MatricesR Programming: Introduction to Matrices
R Programming: Introduction to MatricesRsquared Academy
 
Map reduce (from Google)
Map reduce (from Google)Map reduce (from Google)
Map reduce (from Google)Sri Prasanna
 

What's hot (18)

Stack organization
Stack organizationStack organization
Stack organization
 
Stack linked list
Stack linked listStack linked list
Stack linked list
 
computer notes - Data Structures - 6
computer notes - Data Structures - 6computer notes - Data Structures - 6
computer notes - Data Structures - 6
 
The Stack And Recursion
The Stack And RecursionThe Stack And Recursion
The Stack And Recursion
 
Stack
StackStack
Stack
 
Stack
StackStack
Stack
 
DATA STRUCTURE - STACK
DATA STRUCTURE - STACKDATA STRUCTURE - STACK
DATA STRUCTURE - STACK
 
Stacks in DATA STRUCTURE
Stacks in DATA STRUCTUREStacks in DATA STRUCTURE
Stacks in DATA STRUCTURE
 
Stack
StackStack
Stack
 
Algorithm and Data Structure - Queue
Algorithm and Data Structure - QueueAlgorithm and Data Structure - Queue
Algorithm and Data Structure - Queue
 
Mapreduce: Theory and implementation
Mapreduce: Theory and implementationMapreduce: Theory and implementation
Mapreduce: Theory and implementation
 
Algorithm and Data Structure - Stack
Algorithm and Data Structure - StackAlgorithm and Data Structure - Stack
Algorithm and Data Structure - Stack
 
Rana Junaid Rasheed
Rana Junaid RasheedRana Junaid Rasheed
Rana Junaid Rasheed
 
Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queues
 
What is Stack? Application of Stack
What is Stack? Application of StackWhat is Stack? Application of Stack
What is Stack? Application of Stack
 
R Programming: Introduction to Matrices
R Programming: Introduction to MatricesR Programming: Introduction to Matrices
R Programming: Introduction to Matrices
 
Map reduce (from Google)
Map reduce (from Google)Map reduce (from Google)
Map reduce (from Google)
 
Stack & heap
Stack & heap Stack & heap
Stack & heap
 

Viewers also liked

Engineering thermodynamics
Engineering thermodynamicsEngineering thermodynamics
Engineering thermodynamicsAnand Gadge
 
The Role of Economics in Real-Time Strategy Games
The Role of Economics in Real-Time Strategy GamesThe Role of Economics in Real-Time Strategy Games
The Role of Economics in Real-Time Strategy GamesFabian Samuel
 
Educación de Calidad en la Era Digital
Educación de Calidad en la Era DigitalEducación de Calidad en la Era Digital
Educación de Calidad en la Era DigitalAUGEAmerica
 
Holiday Resorts in Konkan
Holiday Resorts in KonkanHoliday Resorts in Konkan
Holiday Resorts in KonkanIndra Patle
 
Ceasation of hydrologic cycle in tharparkar
Ceasation of hydrologic cycle in tharparkarCeasation of hydrologic cycle in tharparkar
Ceasation of hydrologic cycle in tharparkarTayyaba Sohail
 
Brazilian State-owned Banks and Climate Change
Brazilian State-owned Banks and Climate ChangeBrazilian State-owned Banks and Climate Change
Brazilian State-owned Banks and Climate ChangeFGV Brazil
 
ISCV 2012 Cycle: Supply Chain Management
ISCV 2012 Cycle: Supply Chain ManagementISCV 2012 Cycle: Supply Chain Management
ISCV 2012 Cycle: Supply Chain ManagementFGV Brazil
 

Viewers also liked (12)

Sandra F-3
Sandra F-3Sandra F-3
Sandra F-3
 
Engineering thermodynamics
Engineering thermodynamicsEngineering thermodynamics
Engineering thermodynamics
 
Integradora 1
Integradora 1Integradora 1
Integradora 1
 
The Role of Economics in Real-Time Strategy Games
The Role of Economics in Real-Time Strategy GamesThe Role of Economics in Real-Time Strategy Games
The Role of Economics in Real-Time Strategy Games
 
Educación de Calidad en la Era Digital
Educación de Calidad en la Era DigitalEducación de Calidad en la Era Digital
Educación de Calidad en la Era Digital
 
Holiday Resorts in Konkan
Holiday Resorts in KonkanHoliday Resorts in Konkan
Holiday Resorts in Konkan
 
Ceasation of hydrologic cycle in tharparkar
Ceasation of hydrologic cycle in tharparkarCeasation of hydrologic cycle in tharparkar
Ceasation of hydrologic cycle in tharparkar
 
Relatório de vendas MetaMarx
Relatório de vendas MetaMarxRelatório de vendas MetaMarx
Relatório de vendas MetaMarx
 
Pr oom2009!!!11 b
Pr oom2009!!!11 bPr oom2009!!!11 b
Pr oom2009!!!11 b
 
Brazilian State-owned Banks and Climate Change
Brazilian State-owned Banks and Climate ChangeBrazilian State-owned Banks and Climate Change
Brazilian State-owned Banks and Climate Change
 
ISCV 2012 Cycle: Supply Chain Management
ISCV 2012 Cycle: Supply Chain ManagementISCV 2012 Cycle: Supply Chain Management
ISCV 2012 Cycle: Supply Chain Management
 
Skruvpåle broschyr
Skruvpåle broschyrSkruvpåle broschyr
Skruvpåle broschyr
 

Similar to Stack

Stacks-and-Queues.pdf
Stacks-and-Queues.pdfStacks-and-Queues.pdf
Stacks-and-Queues.pdfTobyWtf
 
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueWhat is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueBalwant Gorad
 
ADT STACK and Queues
ADT STACK and QueuesADT STACK and Queues
ADT STACK and QueuesBHARATH KUMAR
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manualnikshaikh786
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queueRajkiran Nadar
 
Ds
DsDs
DsAcad
 
Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptxline24arts
 
Difference between stack and queue
Difference between stack and queueDifference between stack and queue
Difference between stack and queuePulkitmodi1998
 
Module 2 ppt.pptx
Module 2 ppt.pptxModule 2 ppt.pptx
Module 2 ppt.pptxSonaPathak4
 
Chapter 5 Stack and Queue.pdf
Chapter 5 Stack and Queue.pdfChapter 5 Stack and Queue.pdf
Chapter 5 Stack and Queue.pdfGirT2
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arraystameemyousaf
 

Similar to Stack (20)

Stacks-and-Queues.pdf
Stacks-and-Queues.pdfStacks-and-Queues.pdf
Stacks-and-Queues.pdf
 
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueWhat is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
 
ADT STACK and Queues
ADT STACK and QueuesADT STACK and Queues
ADT STACK and Queues
 
DS UNIT 1.pdf
DS UNIT 1.pdfDS UNIT 1.pdf
DS UNIT 1.pdf
 
DS UNIT 1.pdf
DS UNIT 1.pdfDS UNIT 1.pdf
DS UNIT 1.pdf
 
04 stacks
04 stacks04 stacks
04 stacks
 
Queues
QueuesQueues
Queues
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
 
Ds
DsDs
Ds
 
Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptx
 
Difference between stack and queue
Difference between stack and queueDifference between stack and queue
Difference between stack and queue
 
Module 2 ppt.pptx
Module 2 ppt.pptxModule 2 ppt.pptx
Module 2 ppt.pptx
 
Stack and queue
Stack and queueStack and queue
Stack and queue
 
Data structure by Digvijay
Data structure by DigvijayData structure by Digvijay
Data structure by Digvijay
 
Stack Data Structure
Stack Data StructureStack Data Structure
Stack Data Structure
 
Chapter 5 Stack and Queue.pdf
Chapter 5 Stack and Queue.pdfChapter 5 Stack and Queue.pdf
Chapter 5 Stack and Queue.pdf
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays
 
Unit 3 stack
Unit   3 stackUnit   3 stack
Unit 3 stack
 

More from maamir farooq (20)

Ooad lab1
Ooad lab1Ooad lab1
Ooad lab1
 
Lesson 03
Lesson 03Lesson 03
Lesson 03
 
Lesson 02
Lesson 02Lesson 02
Lesson 02
 
Php client libray
Php client librayPhp client libray
Php client libray
 
Swiftmailer
SwiftmailerSwiftmailer
Swiftmailer
 
Lect15
Lect15Lect15
Lect15
 
Lec 7
Lec 7Lec 7
Lec 7
 
Lec 6
Lec 6Lec 6
Lec 6
 
Lec 5
Lec 5Lec 5
Lec 5
 
J query 1.7 cheat sheet
J query 1.7 cheat sheetJ query 1.7 cheat sheet
J query 1.7 cheat sheet
 
Assignment
AssignmentAssignment
Assignment
 
Java script summary
Java script summaryJava script summary
Java script summary
 
Lec 3
Lec 3Lec 3
Lec 3
 
Lec 2
Lec 2Lec 2
Lec 2
 
Lec 1
Lec 1Lec 1
Lec 1
 
Css summary
Css summaryCss summary
Css summary
 
Manual of image processing lab
Manual of image processing labManual of image processing lab
Manual of image processing lab
 
Session management
Session managementSession management
Session management
 
Data management
Data managementData management
Data management
 
Content provider
Content providerContent provider
Content provider
 

Recently uploaded

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 

Recently uploaded (20)

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 

Stack

  • 1. http://www.tutorialspoint.com/data_structures_algorithms/stack_algorithm.htm Copyright © tutorialspoint.com DATA STRUCTURE - STACKDATA STRUCTURE - STACK A stack is an abstract data type ADT, commonly used in most programming languages. It is named stack as it behaves like a real-world stack, for example − deck of cards or pile of plates etc. A real-world stack allows operations at one end only. For example, we can place or remove a card or plate from top of the stack only. Likewise, Stack ADT allows all data operations at one end only. At any given time, We can only access the top element of a stack. This feature makes it LIFO data structure. LIFO stands for Last-in-first-out. Here, the element which is placed insertedoradded last, is accessed first. In stack terminology, insertion operation is called PUSH operation and removal operation is called POP operation. Stack Representation Below given diagram tries to depict a stack and its operations − A stack can be implemented by means of Array, Structure, Pointer and Linked-List. Stack can either be a fixed size one or it may have a sense of dynamic resizing. Here, we are going to implement stack using arrays which makes it a fixed size stack implementation. Basic Operations Stack operations may involve initializing the stack, using it and then de-initializing it. Apart from these basic stuffs, a stack is used for the following two primary operations − push − pushing storing an element on the stack. pop − removing accessing an element from the stack. When data is PUSHed onto stack. To use a stack efficiently we need to check status of stack as well. For the same purpose, the
  • 2. following functionality is added to stacks − peek − get the top data element of the stack, without removing it. isFull − check if stack is full. isEmpty − check if stack is empty. At all times, we maintain a pointer to the last PUSHed data on the stack. As this pointer always represents the top of the stack, hence named top. The top pointer provides top value of the stack without actually removing it. First we should learn about procedures to support stack functions − peek Algorithm of peek function − begin procedure peek return stack[top] end procedure Implementation of peek function in C programming language − int peek() { return stack[top]; } isfull Algorithm of isfull function − begin procedure isfull if top equals to MAXSIZE return true else return false endif end procedure Implementation of isfull function in C programming language − bool isfull() { if(top == MAXSIZE) return true; else return false; } isempty Algorithm of isempty function − begin procedure isempty if top less than 1 return true else return false endif
  • 3. end procedure Implementation of isempty function in C programming language is slightly different. We initialize top at -1, as index in array starts from 0. So we check if top is below zero or -1 to determine if stack is empty. Here's the code − bool isempty() { if(top == -1) return true; else return false; } PUSH Operation The process of putting a new data element onto stack is known as PUSH Operation. Push operation involves series of steps − Step 1 − Check if stack is full. Step 2 − If stack is full, produce error and exit. Step 3 − If stack is not full, increment top to point next empty space. Step 4 − Add data element to the stack location, where top is pointing. Step 5 − return success. if linked-list is used to implement stack, then in step 3, we need to allocate space dynamically. Algorithm for PUSH operation A simple algorithm for Push operation can be derived as follows − begin procedure push: stack, data if stack is full return null endif top ← top + 1 stack[top] ← data end procedure Implementation of this algorithm in C, is very easy. See the below code −
  • 4. void push(int data) { if(!isFull()) { top = top + 1; stack[top] = data; }else { printf("Could not insert data, Stack is full.n"); } } Pop Operation Accessing the content while removing it from stack, is known as pop operation. In array implementation of pop operation, data element is not actually removed, instead top is decremented to a lower position in stack to point to next value. But in linked-list implementation, pop actually removes data element and deallocates memory space. A POP operation may involve the following steps − Step 1 − Check if stack is empty. Step 2 − If stack is empty, produce error and exit. Step 3 − If stack is not empty, access the data element at which top is pointing. Step 4 − Decrease the value of top by 1. Step 5 − return success. Algorithm for POP operation A simple algorithm for Pop operation can be derived as follows − begin procedure pop: stack if stack is empty return null endif data ← stack[top] top ← top - 1 return data end procedure Implementation of this algorithm in C, is shown below − int pop(int data) {
  • 5. if(!isempty()) { data = stack[top]; top = top - 1; return data; }else { printf("Could not retrieve data, Stack is empty.n"); } } For a complete stack program in C programming language, please click here. Loading [MathJax]/jax/output/HTML-CSS/jax.js