0% found this document useful (0 votes)
9 views18 pages

Chapter 6 - Stack and Queues

This document covers the implementation and concepts of stacks and queues as abstract data types (ADTs). It explains the Last-In First-Out (LIFO) principle for stacks and the First-In First-Out (FIFO) principle for queues, along with their respective operations and implementations using linked lists. Additionally, it includes exercises related to stacks and queues to reinforce understanding.

Uploaded by

hadytarabay12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views18 pages

Chapter 6 - Stack and Queues

This document covers the implementation and concepts of stacks and queues as abstract data types (ADTs). It explains the Last-In First-Out (LIFO) principle for stacks and the First-In First-Out (FIFO) principle for queues, along with their respective operations and implementations using linked lists. Additionally, it includes exercises related to stacks and queues to reinforce understanding.

Uploaded by

hadytarabay12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Data Structures and Algorithms

Chapter 6 – Stack and Queues

Dr. Georges Badr

1
Outline

• Stacks:
– implementation with linked lists
• Queues:
– implementation with linked lists
• Exercises
STACKS

3
Introduction
• A stack is an abstract data type (ADT) where
– the data are added and removed starting from the last input (added) element
– the position of the last element is called top
• Thus, the last element added to the top is the first to be removed
• This is the technique of LIFO i.e. Last‐In First‐Out
• A stack is compared to a stack of plates
• Motivation:
– stacks are adapted for processes that let the data wait for a future treatment
• e.g., calculation of an arithmetic expression in postfix notation (3 2 *)
• stacks are used bycompilers
– stacks can change recursive treatment to iterative treatment
• recursive calls are pushed into stack, and their return is poped from stack
Introduction

•LIFO: Last In, First Out.


•Restricted form of list: Insert and remove only at front of list.
•Notation:
• Insert: PUSH
• Remove: POP
• The accessible element is called TOP.
•Extra operations:
• Empty
• Size

•The elements could be stored in an array or a linked list.

CSC315 - DR MIREILLE MAKARY 5


List-based Stack Implementation
i_Stack.h

//the stack interface


#include "Node.h"

//Stack interface
template<typename T>
class i_Stack {
public:
//push
virtual void push(const T&) = 0;
//pop
virtual T pop() = 0;
//empty
virtual bool empty() = 0;
//size
virtual int size() = 0;
//top
virtual T top() = 0;
};

6
List-based Stack Implementation
Stack.h //override methods
#include "i_Stack.h" void push(const T& x) {
//create a new node
//Linked Stack implementation Node<T>* n = new Node<T>(x, head);
template<typename T> head = n;
sz++;
//cout << "Element pushed succesfully\n";
class Stack : public i_Stack<T> {
}
private:
//head T pop() {//check for empty before calling the function
Node<T>* head;// = nullptr; Node<T>* cur = head;
int sz = 0; head = head->getNext();
T tmp = cur->getData();
public: delete cur;
Stack(Node<T>* h = nullptr) { sz--;
head = h; return tmp;
if (h != nullptr) }
sz = 1;
bool empty() {
}
return sz == 0; //head==nullptr
//destructor
}
~Stack() {
//clear(); int size() {
while (!empty()) return sz;
pop(); }
//sz = 0;
} T top() {
//check for empty before calling the function
return head->getData();
}
}; 7
List-based Stack Implementation
StackMain.cpp

#include<iostream>
using namespace std;

#include"Stack.h

int main() {

Stack<int> st;
st.push(10);
st.push(5);
st.push(3);
st.push(8);
}

8
List-based Stack Implementation - Exercises
//check if a string is palindrom //Use a stack to reverse an entered number.
//Example: N=12345, the result is 54321
bool isPalindrome(char* str) {
int sz = strlen(str);
int reverse (int n)
Stack<char> stk; {
int i; Stack<int> st;
for (i = 0; i < sz / 2; i++) { while (n!=0)
stk.push(str[i]); {
}
if (sz % 2 != 0)
st.push(n%10);
i++; n=n/10;
}
while (i < sz && !stk.empty()) { //while (!stk.empty())
if (stk.pop() != str[i]) int rev = 0;
return false;
i++;
int tmp;
} int i=0;
return true; while (!st.empty())
} {
tmp = st.pop();
rev = rev + tmp * pow(10,i);
i++;
//Calculate the sum of the elements of a stack of integers. }

int sum_Stack (Stack<int> stk) return rev;


{
int s = 0, temp;
}
while (!stk.empty())
{
temp = stk.pop();
s += temp;
}
return s;
}
9
List-based Stack Implementation - Exercises
//Divide the stack into 2 other stacks.
//The 1st one contains the even numbers, the 2nd contains the odd
void divide_stack (Stack<int> stk, Stack<int> &stk1, Stack<int> &stk2)
{
int tmp;
while (!stk.empty())
{
tmp = stk.pop();
if(tmp%2==0)
{
stk1.push(tmp);
}
else{
stk2.push(tmp);
}
}
}

//Copy the elements of an array into a stack

void copyArrToStack (int arr[], int n, Stack<int> &stk)


{
int i;
for (i=0; i<n; i++)
{
stk.push(arr[i]);
}
}
10
List-based Stack Implementation - Exercises
//Write a function to test if an expression is well parenthesized (the parenthesis (), {}, [] are well nested and closed)
bool isBalanced (char * str)
{
Stack<char>st;
char tmp;
int i;
for(i =0; str[i]!='\0';i++)
{
if (str[i] == '(' || str[i] == '[' || str[i] == '{')
st.push(str[i]);
else{
switch (str[i]){
case ')': if(st.empty())
return false;
tmp = st.pop();
if (tmp != '(')
return false;
break;

case ']': if(st.empty())


return false;
tmp = st.pop();
if (tmp != '[')
return false;
break;

case '}': if(st.empty())


return false;
tmp = st.pop();
if (tmp != '{')
return false;
break;
}
}
}
return (st.empty());
} 11
QUEUES

12
Introduction
• A queue is an abstract data type (ADT) in which
– data are added at the end of the queue with the function enqueue(val)
– data are retrieved from the beginning of the queue with the function dequeue()

• This technique of adding and removing from the queue is called FIFO (First In, First Out)

• Example, waiting in a supermarkets checkout line


– the first customer is served first and others enter the line at the end and wait to be served

• Application:
– buffer in a printer where files wait to be printed out
– buffer in a router where packets wait their turn before the transmission on the
network
Introduction

•FIFO: First in, First Out


•Restricted form of list: Insert at one end, remove from the other.
•Notation:
• Insert: Enqueue
• Delete: Dequeue
• First element: Front
• Last element: Rear
•Extra operations:
• Empty
• Size

CSC315 - DR MIREILLE MAKARY 14


List-based Queue Implementation
i_Queue.h
//the Queue interface
#include "Node.h"

template<typename T>

class i_Queue {
public: //all operations are O(1) except clear: O(n) --> in LinkedQueue
virtual void enqueue(const T&) = 0;
virtual const T& dequeue() = 0;
virtual bool empty() = 0;
virtual int size() = 0;
virtual const T& front() = 0;
virtual void clear() = 0;
};

15
List-based Queue Implementation
Queue.h ~Queue() {
clear();
#include "i_Queue.h" sz = 0;
template<typename T> }

class Queue : public i_Queue<T> {


private: //enqueue
Node<T>* head, *tail=nullptr; void enqueue(const T& element) {//O(1)
int sz = 0;
Node<T>* n = new Node<T>(element);
if (empty())
void clear() {
Node<T>* cur = head; head = n;
while (head != nullptr) { else
head = head->getNext(); {
delete cur; tail->setNext(n);
cur = head;
} }
//optional tail = n;
sz = 0; sz++;
tail = nullptr; //cout << element << " was enqueued\n";
} }
public:
Queue(Node<T>* h = nullptr) {
head = h;
if (head != nullptr) {
sz++;
tail = head;
}
}

16
List-based Queue Implementation
//dequeue
const T& dequeue() {//pop_front
//check empty in main
Node<T>* cur = head;
head = head->getNext();
if (head == nullptr) //we had only one element
tail = nullptr;
T tmp = cur->getData();
//delete cur;
//this gives an error when using the queue because the cur no longer exists, and therefore the data
cannot be accessed
sz--;
return tmp;
}

bool empty() {return sz == 0; //head==nullptr}

int size() {return sz;}

const T& front() {


//check if empty in main
return head->getData();
}

17
List-based Queue Implementation
QueueMain.cpp

#include<iostream>
using namespace std;

#include"Stack.h“

int main()
{
Queue<int> Q;
Q.enqueue(5);
Q.enqueue(10);
Q.enqueue(3);
Q.enqueue(8);
}

18

You might also like