Data Structures
Data Structures
1
Data Structures
2
Data Structures (Cont’d)
3
Data Structures (Cont’d)
Data Structure:
4
Data Structures (Cont’d)
Database:
6
Structured Organization of Data
7
Structured Organisation of Data (cont’d.)
Linked lists
Graphs
Trees
Stacks
Queues
Network Science
9
Introduction
Basic data types are groups such as integer, string and
real. Abstract data types are more general.
Linked lists
Graphs
Trees
Stacks
Queues
Network Science
Linked Lists
A linked list organises a collection of data items
(elements) such that elements can easily be added to
and deleted from any position in the list.
Element Next
Element Next
Element Next
NULL
There are also doubly linked lists. They are not in the
scope of this module
13
Linked Lists: Simple Example
Linked Lists: Simple Example
Linked Lists: Simple Example…
Linked Lists: Simple Example…
Linked Lists: Simple Example…
Explanation:
•Each Station has a name (like "Station A") and a reference to the
next_station.
•The TrainRoute class represents our monorail route.
•We can add new stations to the route using add_station.
•We can display the entire route using display_route.
•In the example, we added four stations (A, B, C, and D) to our route and
then displayed the entire route.
Station A -> Station B -> Station C -> Station D -> End of Line
Operations on Linked Lists
Operations such as inserting an element and deleting
an element are easily carried out. Only references to
next elements are updated in these operations.
19
Linked Lists: Insertion
New data
Element Next
Element Next
NULL
20
Linked Lists: Deletion
Element Next
Deleted element
Element Next
Element Next
NULL
21
Python Example
22
Python Example…
23
Python Example…
24
Python Example… (def delete_station)
25
Python Example…
Initial Route:
Station A -> Station B -> Station C -> Station D -> End of Line
26
Outline
Abstract Data Types
Linked lists
Graphs
Trees
Stacks
Queues
Network Science
Graphs
A graph data structure consists of vertices
and elements.
D E G
C I
F H
B J K
A
28
Types of Graphs
Directed graph
Each edge of the graph has a direction (arrow).
Connected graph
A graph in which there exists a path between every
pair of nodes.
Acyclic graph
A graph not containing any cycle.
29
Types of Graphs (cont’d.)
Weighted graph
Each edge has an allotted value (weight).
For example, this weight can represent distance or
duration.
Planar graph
A graph is planar if it can be drawn in 2-D so that
the edges do not cross over each other.
30
Example Graph
Intersections (Nodes):
A: Town Hall
B: Library
C: School
D: Park
E: Shopping Mall
Roads (Edges):
A <-> B: Main St.
A <-> C: First Ave.
B <-> D: Second Ave.
C <-> D: Third St.
C <-> E: Fourth St.
31
Example Graph (cont’d.)
class Graph:
def __init__(self):
self.adjacency_list = {}
32
Example Graph (cont’d.)
def display(self):
"""Display the graph."""
for node, edges in self.adjacency_list.items():
connections = ", ".join([f"{edge[0]} ({edge[1]})" for edge in edges])
print(f"{node} -> {connections}")
List Comprehension:
[f"{edge[0]} ({edge[1]})" for edge in edges]
33
Example Graph (cont’d.)
def display(self):
"""Display the graph."""
for node, edges in self.adjacency_list.items():
connections = ", ".join([f"{edge[0]} ({edge[1]})" for edge in edges])
print(f"{node} -> {connections}")
String Formatting:
The f before the string indicates it's an f-string (formatted string literal)
which is a feature introduced in Python 3.6. It allows embedded
expressions inside string literals. Inside the f-string:
{edge[0]}: This will be replaced by the first element of the edge (i.e.,
destination node).
{edge[1]}: This will be replaced by the second element of the edge (i.e.,
road name).
34
Example Graph (cont’d.)
def display(self):
"""Display the graph."""
for node, edges in self.adjacency_list.items():
connections = ", ".join([f"{edge[0]} ({edge[1]})" for edge in edges])
print(f"{node} -> {connections}")
Joining:
", ".join(...)
The join() method is a string method that takes a list of strings and
concatenates them into a single string. The string on which the join()
method is called will be used as a separator. Here, it's called on the string
", ", so it will concatenate the list of strings generated by the list
comprehension with a comma followed by a space.
35
Example Graph (cont’d.)
# Using the Graph to represent the road network:
road_network = Graph()
36
Example Graph (cont’d.)
In this implementation:
The Graph class has an adjacency list to represent nodes and their
connections.
37
Possible Applications of Graphs
Road networks
Office buildings (access, fire escapes, etc.)
Structures and frameworks
Social networks (for example, those used to deal
with sicknesses such as SARS and AIDS)
38
Review Questions
39
Answers
40
Outline
Abstract Data Types
Linked lists
Graphs
Trees
Stacks
Queues
Network Science
Trees
42
Example: Classification tree
Bridges
N1
N2 N3 N4
Country USA Switzerland UK
N5 N6 N7 N8
Type Cable- Pre-stressed Cable- Arch
stayed stayed
Name Tacoma
Narrows Lutrive London
43
Example: Classification tree
Example: Classification tree (Class Node)
Example: Classification tree (Class Node)
Root
|
|-- USA
|
|-- Suspension
|
|-- Medium
|
|-- Brooklyn Bridge
In this example:
UK
Arch
Short
London
Graphs and Trees
Connected acyclic
graph (Tree) Directed graph
50
Outline
Abstract Data Types
Linked lists
Graphs
Trees
Stacks
Queues
Network Science
Stacks
Stacks are LIFO (Last In First Out) data structures.
Operations on stacks are to add an element to the top
of the stack (push) and extract an element from the top
of the stack (pop).
Add an element
(push) Remove an element
(pop)
52
Stacks in Simple Terms
Stacks in Context of Parking
Stack: Example
Stack: Example..
Another Example of Stacks
Stacks can be used to keep track of changes in order
to be able to carry out backtracking (undo).
57
Outline
Abstract Data Types
Linked lists
Graphs
Trees
Stacks
Queues
Network Science
Queues
Queues are FIFO (First In First Out) data structures.
Standard operations are Enqueue (add element to
the tail of the queue) and Dequeue (take out
element from the front of the queue).
Add an element
(Enqueue)
Remove an element
(Dequeue)
59
Queues
Queues are a common data structure that follow the First In, First Out (FIFO)
principle.
Simple Analogy: Imagine a line of people waiting at a bank. The first person in
line is the first to be served, and as new people arrive, they join the end of the
line. That's how a queue works.
Other Example:
Imagine a toll booth on a highway where vehicles have to stop and pay a toll
before proceeding. During rush hours or holidays, multiple vehicles line up to
pass through the toll booth. The first vehicle in line will be the first to pay and
proceed, and vehicles that arrive later join the end of the queue. This behavior
follows the First In, First Out (FIFO) principle of a Queue.
In this context:
Enqueue: A vehicle arriving at the toll booth and getting in line.
Dequeue: A vehicle paying the toll and leaving the queue.
Peek (or Front): Checking which vehicle is next in line to pay.
60
Remarks
Abductive tasks
Abductive engineering tasks are well supported by the
abstract data types.
Exponential complexity
The presence of stacks in the loops of a program may
indicate exponential complexity.
61
Review Questions
62
Answers
What is the difference between a stack and a
queue?
In a stack, the last data entry is used first while
in a queue, the first data entry is used first
Name two uses for stacks.
Undo and backtracking
What feature of trees makes reasoning with trees
easier than with other types of graphs?
A tree graph contains no cycles (acyclic) and
therefore, there is no risk of endless loops.
63
Discussion
Once data is organized into forms such as trees,
stacks and queues, standard algorithms can be
used to process them.
64
Outline
Abstract Data Types
Linked lists
Graphs
Trees
Stacks
Queues
Network Science
Network Science
Networks
A group of elements interconnected by links.
Random Networks
A network which has a random distribution between the
number of elements and the number of links.
Number of Nodes
Characteristic Node
Number of Links
66
Examples of Random Networks
Roads and crossroads
Rooms, doors and corridors in a building
Links and elements of a structure
Water distribution networks
Any situation where the geometric proximity is
important. For example, the length of the links
significantly contributes to costs.
67
Scale-Free Networks
Scale-Free Networks
A network with a logarithmic relationship between the
number of elements and the number of links.
Number of elements Number of elements (log)
Number of Number of
Links links (log)
69
70
Properties of a Scale-Free Network
The presence of “hubs” – a small number of
elements with many links
The small-world phenomenon (nodes can be
accessed through a small number of links.)
Elements with many links are preferred during
the growth of a network
Robust in the event of a random failure
Sensitive to targeted attacks
71
Questions
• What is the point of having standard data structures?
There are libraries of functions for using them and they
have known strengths and weaknesses.
• What is the danger of implementing stacks?
Stacks may lead to systematic backtracking and this
causes exponential complexity.
• When are scale-free networks robust and when are
they vulnerable?
They are robust in a random attack (or breakdown) and
they are vulnerable in a targeted attack.
72
Further Reading
Kruse, R. L., Leung, B. P. and Tondo, C. L. Data
Structures and Program Design in C, Englewood
Cliffs NJ: Prentice Hall, 1991
74
Extra Remarks…
Exponential complexity
75
Extra Remarks…
Exponential complexity
76
Extra Remarks…
Exponential complexity
- To House B: 2 routes
- To House C: 2 x 2 = 4 routes
- To House D: 2 x 2 x 2 = 8 routes
- And so on...