7-Stack
7-Stack
Programming ii
Stack data structure
1
Stack
2
Outline
❑ A Brief of Outline
▪ What is Stack?
▪ Examples
3
What is Stack?
❑ Definition
▪ Stack is a data structure that stores data in such a way that the element
stored last will be retrieved first
▪ etc.
5
Queue Vs. Stack
❑ Differences
push(‘A’) pop()
top
enqueue(‘F’)
dequeue()
rear
front
Stack Queue
6
Stack Operations
❑ Operation
▪ A stack is controlled by two main operations which implement the LIFO method
▪ Insertion pop()
push(‘A’)
▪ Add element to the stack (add to the top)
▪ The variable TOP is used to keep track of the top element in the stack
7
Stack Operations
❑ More operations
8
Stack Implementation
❑ Implementation
top
▪ An integer type variable called TOP which stores the index of the top element of the stack
2. As a Linked List
▪ A linked list to store data
▪ A pointer variable called TOP which points to the top element of the list
9
2. Stack as Linked List
Stack as Linked List
➢ Dynamic
▪ It can grow or shrink at runtime
10
Stack Implementation
❑ Stack as a Linked List
11
Stack Implementation
❑ Stack as a Linked List
▪ Implementing stack as a linked list is just like implementing a linked list with some choices
Choice 1
▪ Element can be only removed from the beginning of the list (pop operation)
Choice 2
▪ Element can be only removed from end of the list (pop operation)
13
Stack Implementation: Examples
❑ Stack as a Linked List
How to implement this Stack?
top
14
Q and A
15
Homework
❑ Reading: Sorting Algorithms
16
Example 1: Class activity
❑ Stack as Array void push(int item){
if(isFull()){
cout<<"\n\tStack overflow! can't add";
}else{
▪ Modify code at Part 3 to obtain the same output below //your code
}
#include<iostream> bool isEmpty(){ }
using namespace std; if(top==-1){ void pop(){
const int SIZE=3; return true; if(isEmpty()){
int stack[SIZE]; } cout<<"\n\tStack underflow! can't remove";
int top=-1; return false; }else{
} //your code
bool isEmpty(); bool isFull(){ }
bool isFull(); if(top==SIZE-1){ }
void push(int item); return true; void display(){
void pop(); } cout<<"\n";
return false; cout<<"Display data in stack from top: ";
void display();
}
Part 2 if(!isEmpty()){
int main(){ //your code
push(2); }else{
push(5); cout<<" Stack is empty\n";
push(7); }
push(1); } Part 3
display();
pop();
pop();
pop();
pop();
display(); 17
}
Part 1 Expected Output
Example 1: SOLUTION
❑ Stack as Array void pop(){
if(isEmpty()){
cout<<"\n\tStack underflow! can't remove";
➢ ----
19
Attendance record
• Attendance submit:
forms.gle/J3XzFbw3cMe1uBrf6
• Student review & QA: 3:10 – 3:40pm
• Quiz about Queue: 3:45 – 4:00pm (on Moodle)
• Stack lecture 20