0% found this document useful (0 votes)
21 views43 pages

L02b ADT Stack and Queue

The document discusses Abstract Data Types (ADTs) and their implementation in C++, focusing on data structures like stacks and queues. It explains the concept of ADTs as collections of data with specified operations, the use of C++ Standard Template Library (STL) for generic programming, and provides examples of stack and queue operations. Additionally, it covers practical applications such as bracket matching and evaluating arithmetic expressions using stacks.
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)
21 views43 pages

L02b ADT Stack and Queue

The document discusses Abstract Data Types (ADTs) and their implementation in C++, focusing on data structures like stacks and queues. It explains the concept of ADTs as collections of data with specified operations, the use of C++ Standard Template Library (STL) for generic programming, and provides examples of stack and queue operations. Additionally, it covers practical applications such as bracket matching and evaluating arithmetic expressions using stacks.
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/ 43

TIC2001 Data Structures and Algorithms

Lecture Note #2b

Abstract Data Type


Outline
1. Abstract Data Type
1.1 Data Structure
1.2 Understanding ADT

2. C++ STL and Interface

3. Stack and Queue

2
1 Abstract Data Type

Collection of data + set of operations


on the data
1.1 Data Structure
 Data structure is a construct that can be defined within a
programming language to store a collection of data
 Arrays, which are built into C++, are data structures
 We can create other data structures. For example, we want a
data structure (a collection of data) to store both the names and
salaries of a collection of employees

class Employee {
const int MAX_NUMBER = 500;
private:
String name;
double salary;
public:
double cpf();


}

Employee * workers = new Employee[100];

4
1.2 Abstract Data Type (ADT) (1/4)
 An ADT represent a collection of data together with a
specification of a set of operations (functional
abstraction) on the data
 Functional abstraction  The specifications indicate what
ADT operations do, not how to implement them
 Also does not specify how the data is to be stored

Collection Spec. of a
ADT of data set of
operations

 Data structures/algorithms is then the how to implement


them part

5
1.2 Abstract Data Type (ADT) (2/4)
 When a program needs data operations that are not
directly supported by a language, you need to create
your own ADT
 You should first design the ADT by carefully specifying
the operations before implementation

6
1.2 Abstract Data Type (ADT) (3/4)
 Example: A water dispenser as an ADT
 Data: water
 Operations: chill, crush, cube,
and isEmpty
 Data structure: the internal
structure of the dispenser
 Walls: made of steel
The only slits in the walls:
 Input: water
 Output: chilled water, crushed
ice, or ice cubes.
Crushed ice can be made in many ways.
We don’t care how it was made

 Using an ADT is like using a


vending machine.
7
1.2 Abstract Data Type (ADT) (4/4)
 A WALL of ADT operations hides a data structure
from the program that uses it
 An interface is what a program/module/class should
understand on using the ADT

8
Eg: Primitive Types as ADTs (1/2)
 C++’s predefined data types are ADTs
 Representation details are hidden which aids ease of
usage and portability
 Examples: int, bool, double

--
||

*
int && bool
+
/
++ !

int type with the operations bool type with the operations
(e.g.: --, /) defined on it. (e.g.: &&) defined on it.

9
C++ program

STL
Driver

ADT main.cpp

Specification Implementation

.h files .cpp files


10
C++ Standard Template Library (STL)
 The C++ STL (Standard Template Library) is a
powerful set of C++ template classes to provide
general-purpose classes and functions with
templates that implement many popular and
commonly used algorithms and data structures
like vectors, lists, queues, and stacks.
 One of the key benefits of the STL is that it
provides a way to write generic, reusable code
that can be applied to different data types. This
means that you can write an algorithm once, and
then use it with different types of data without
having to write separate code for each type.
11
2 Interface

Specifying related methods


2.1 Using Interface to define ADT
 Interfaces provide a way to specify a common set of
operations for possibly unrelated classes and can be
used to specify an ADT
 Example: Symbol Table
void insert(Key k, Value v); // insert (k,v) into table
Value search(Key k); // get value paired with k
void delete(Key k); // remove key k (and value)
bool contains(Key k) ; // is there a value for k?
int size(); // number of (k,v) pairs

A class is said to implement the interface if it provides


implementations for ALL the methods in the interface

13
ListNode.h (Interface)
class ListNode {
private:
int _item;
ListNode* _next;

public:
ListNode(int);
int content() { return _item; };
friend class List;
};
14
List.h (Interface)
class List{
private:
int _size;
ListNode* _head;
public:
List() {
~List();
_size = 0; void insertHead(int);
_head = NULL; void removeHead();
}; void printAlternate();
int count(int);
int headItem();
};
15
ListNode.cpp (implementation)
#include <iostream>
#include "simpleIntLinkedList.h"
using namespace std;

ListNode::ListNode(int n) {
_item = n;
_next = NULL;
}

16
List.cpp (implementation)
void List::insertHead(int n){
ListNode* aNewNode = new ListNode(n);
aNewNode->_next = _head;
_head = aNewNode;
_size++;
};

void List::removeHead() {
if (_size > 0) {
ListNode* temp = _head;
_head = _head->_next;
delete temp;
_size--;
}
}
17
Driver
#include <iostream>
#include "simpleIntLinkedList.h"
using namespace std;

int main(){
List l;

l.insertHead(123);
l.insertHead(11);
l.insertHead(9);
l.insertHead(1);
l.insertHead(9);

18
Driver
cout << "Print alternating elements: ";
l.printAlternate();
cout << endl;

for (int i = 0; i < 5; i++) {


cout << "The number of occurrences of 9 in the list: "
cout << l.count(9) << endl << endl;
l.removeHead();
cout << "Remove head from the list" << endl << endl;
}

return 0;

19
1-5 Stacks

Last-In-First-Out (LIFO)
1 Stack ADT: Operations
 A Stack is a collection of data that is accessed in
a last-in-first-out (LIFO) manner
 Major operations: “push”, “pop”, and “peek”.

item

Pop()
push(item)

Peek()

stack

21
1 Stack ADT: Uses
 Calling a function
 Before the call, the state of computation is saved on the
stack so that we will know where to resume
 Recursion
 Matching parentheses
 Evaluating arithmetic expressions (e.g. a + b – c) :
 postfix calculation
 Infix to postfix conversion
 Traversing a maze  Will look at this later in the
course

22
1 Stack: Usage

s d
Stack s;
s.push (1);
s.push (2);
s.push (3); 3
d = s.peek ();
s.pop ();
s.push (4);
s.pop (); 3
4
2
1

23
2 Stack Implementation: Array
 Use an Array with a top index pointer

StackArr

arr
0 1 2 3 4 5 6 7 8 9
push(“6”);
1 2 3 4 5 6 7 push(“7”);

pop();
10
maxsize
top

24
3 Stack Implementation: Linked List (1/6)
 A class can be defined in 2 ways:
 via inheritance  we will not look into this
 via composition, as shown below

class A {
public B b = new B (…); // A is composed of instance of B

}

 Let’s make BasicLinkedList an instance attribute in


the LinkedList based implementation for Stack!

25
3 Stack Implementation: Linked List (2/6)
 (Composition): Use BasicLinkedList

StackLL – class for our linked list implementation

list
Instance attribute
Top = Front of List

BasicLinkedList
head num_nodes
4

a1 a2 a3 a4

26
5 Application 1: Bracket Matching
 Ensures that pairs of brackets are properly matched

An example: {a,(b+f[4])*3,d+f[5]}

Incorrect examples:

(..)..) // too many close brackets

(..(..) // too many open brackets

[..(..]..) // mismatched brackets

27
5 Application 1: Bracket Matching
create empty stack
for every char read Q: What type of error does
{ the last line test for?
if open bracket then
A: too many closing brackets
push onto stack B: too many opening brackets
if close bracket, then C: bracket mismatch
if doesn’t match or underflow then flag error
else pop from the stack [ ]
}
(
[ ) ]
if stack is not empty then flag error
Example { }
{ a -( b + f [ 4 ] ) * 3 * d + f [ 5 ] }
Stack

28
5 Applicn 2: Evaluating Arithmetic Expression
 Terms
 Expression: a=b+c*d
 Operands: a, b, c, d
 Operators: =, +, –, *, /, %
 Precedence rules: Operators have priorities over
one another as indicated in a table (which can be
found in most books)
 Example: * and / have higher precedence over + and –.
 For operators at the same precedence (such as * and
/), we process them from left to right

29
5 Applicn 2: Evaluating Arithmetic Expression

Infix : operand1 operator operand2


Prefix : operator operand1 operand2
Postfix : operand1 operand2 operator

Ambiguous, need () Unique interpretation


or precedence rules postfix
(2+3)*4 2 3 + 4 *
infix

2+3*4

2+(3*4) 2 3 4 * +

30
5 Applicn 2: Evaluating Arithmetic Expression
Algorithm: Evaluating Postfix expression with stack
Create an empty stack Infix postfix
for each item of the expression, 2 * (3 + 4) 2 3 4 + *
if it is an operand,
push it on the stack
if it is an operator, 2 s.push(2)
pop arguments from stack; 3 s.push(3)
perform the operation; 4 s.push(4)
push the result onto the stack + arg2 = s.pop ()
Stack arg1 = s.pop ()
s.push (arg1 + arg2)
* arg2 = s.pop ()
arg1 = s.pop ()
arg1
s.push (arg1 * arg2)
32
4
arg2
3 7
47
2 14
31
6-9 Queues

First-In-First-Out (FIFO)
6 Queue ADT: Operations
 A Queue is a collection of data that is accessed
in a first-in-first-out (FIFO) manner
 Major operations: “poll” (or “dequeue”), “offer” (or
“enqueue”), and “peek”.

poll()
offer(item)

Back of
Front of
queue
queue
queue
peek()

27
6 Queue ADT: Uses
 Print queue
 Simulations
 Breadth-first traversal of graph  look at this
later in the course
 Checking palindromes - for illustration only as it
is not a real application of queue

34
6 Queue: Usage

Queue q;
q.offer (“a”);
q.offer (“b”); q
d a
q.offer (“c”);
d = q.peek ();
a b c e
q.poll ();
front
q.offer (“e”); back

q.poll ();

35
7 Queue Implementation: Array
 Use an Array with front and back indices

QueueArr – class that implements Queue using array

arr
0 1 2 3 4 5 6 7 8 9
offer(“F”);
A B C D E F G offer(“G”);

poll();
10
maxsize
front back

36
7 Queue Implementation: Array (2/7)
 “Circular” Array needed to recycle space
0 1 2 3 4 5 6 7 8 9

Given a queue A B C D E F G

front
back

9 0 front

8 1
back A
B To advance the indexes, use
front = (front+1) % maxsize;
C 2
7 back = (back+1) % maxsize;
G D
F E 3
6
5 4
37
7 Queue Implementation: Array (3/7)
 Question: what does (front == back) mean?
A: Full queue
B: Empty queue C: Both A and B
C: Both A and B
D: Neither A nor B

38
7 Queue Implementation: Array (4/7)
 Ambiguous full/empty state
Queue e f c d Queue
Empty F F Full
State B B State

Solution 1 – Maintain queue size or full status


size 0 size 4

Solution 2 (Used in our codes) – Leave a gap!

Don’t need the size field this way e c d

Full Case: (((B+1) % maxsize) == F) B F


Empty Case: F == B

39
8 Queue Implementn: Linked List
 Use TailedLinkedList
 Do not use BasicLinkedList as we would like to use
addBack() of TailedLinkedList.
QueueLL – class of LinkedList based implementation of Queue

list

TailedLinkedList
head num_nodes tail
4

a1 a2 a3 a4

40
10 Palindromes

Application using both Stack and


Queue
10 Application: Palindromes (1/3)
 A string which reads the same either left to right,
or right to left is known as a palindrome
 Palindromes: “radar”, “deed”, “aibohphobia”
 Non-palindromes: “data”, “little”

input “c1 c2 c3 c4 c5”


Algorithm
Given a string, use:
top
a Stack to reverse its order
stack < c5, c4, c3, c2, c1 >
a Queue to preserve its order
Queue < c , c , c , c , c >
1 2 3 4 5
Check if the sequences are the same front
tail

42
Summary
 We can simply use array or linkedlist to
achieve what we want without creating the
Stack and Queue ADT.
 But their names immediately let us know
what they are suppose to achieve.
 Most of the time, stack and queue help us to
improve our algorithms and their efficiency.

43

You might also like