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

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 

Recently uploaded (20)

Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 

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