0% found this document useful (0 votes)
8 views

Data Structures II

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Data Structures II

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Module 4. Data Structures Pt.

2
Data structures continue to play a crucial role in computer science, enabling efficient
data management and manipulation. Building upon the foundation laid in Part 1, this
module delves further into advanced data structures such as stacks, queues and
linked lists.

In this module, you will explore:

● Discover the functionality and structure of lists and arrays, and how to
manipulate them in different programming environments.
● Gain insights into linked lists, understanding how to build and operate
them, including insertion, deletion, and traversal.
● Learn about the structure and functionality of stacks, queues, and binary
trees, and how they can be utilised in programming.
● Discover the principles of graphs, sets, and hash tables, and understand
how to manipulate them in various programming environments.
● Design and manipulate user-defined data structures, integrating them into
real-world applications.

To enhance your understanding, we have tailored specific learning activities:

● Create an array and perform basic operations like insertion and deletion
● Implement stacks and queues using C++.
● Build a singly linked list and perform operations like insertion, deletion, and
traversal.

Subject Learning Outcomes

The material in this module relates to the following subject learning outcomes:

​ SLO 2: Gain the ability to create and modify basic data structures such as
arrays and linked lists, along with performing operations like insertion,
deletion, and traversal.

Student Expectations
During this module, you are expected to spend time working through the prescribed
material prior to attending class. This will enable a more valuable discussion to take
place in online tutorials or conferences, where you will be able to discuss concepts,
present ideas and explore information collaboratively in greater depth.

Accordingly, it is suggested that you allow:

4 hours for facilitated study. This includes guided facilitated study, watching or
attending course lectures (live or pre-recorded), responding to facilitator feedback.

8 hours for personal study. This includes reading through course material,
undertaking learning activities and exploring additional related resources.

Topic 1. Lists and Arrays

Key takeaways from this topic...

1. Lists can be either static or dynamic. Static lists have a fixed size, while
dynamic lists (dynamic arrays) can grow or shrink at runtime.
2. Operations like insertion and deletion are fundamental to understanding how
lists and arrays work.
3. Lists and arrays are used in various applications such as managing
databases, building temporary data storage, and data retrieval.

Learner Guide
The Learner Guide provides the core knowledge for this topic. Work through the
materials and be prepared to discuss these in your forums, tutorials or classes.

Expand All

Panels

Collapse All

Panels

Section 1: Understanding Fundamental Concepts

For a programmer, grasping foundational concepts such as data structures is crucial.


Specifically, lists and arrays serve as vital tools, operating like containers where you
can neatly arrange and manage a plethora of items or elements. In this guide, we
shall embark on a journey to comprehensively explore lists and arrays, using some
practical examples and a real-world case study to cement your understanding.

Understanding Lists

In the programming lexicon, a list stands as a dynamic data structure capable of


holding an ordered collection of items, which can vary vastly in type. These lists are
a cornerstone in the programming domain, renowned for their versatility and
efficiency in managing large volumes of data. Let’s look deeper into the
characteristics that make lists so essential:

● Dynamic Size
○ A list is akin to a magic bag that adjusts its size to
accommodate or remove items as necessary, showcasing a
dynamic nature.
○ Example: Imagine creating a to-do list where you can
continually add new tasks and remove completed ones without
any restriction.
● Ordered Collection
○ Lists are known to maintain a systematic order, ensuring every
item is accessible based on its position or rank in the list.
○ Example: Consider a playlist where songs are arranged in a
specific order, allowing you to find and play any song based on
its position in the list.

Understanding Arrays

Arrays stand as another pivotal data structure, designed to hold more than one value
at a time. They can be visualised as a collection of variables, each identified with a
unique index number, facilitating rapid access. The primary attributes of arrays
include:

● Fixed Size
Contrary to lists, arrays in C++ have a fixed size, which is determined at
the time of creation and cannot be changed thereafter. It's a limitation that
requires the size to be known at compile time. However, you can use
vectors in C++ if you need a dynamic size similar to lists.
● Index-Based Access
In C++ arrays, each element is identified by a unique index number,
allowing swift and direct access to any element based on its position in the
array.

Further Reading

Data Structures in C++ | Array | Linked List | Stack

Links to an external site.

Depending on your project requirements, it is important to choose the right data


structure for your project. Explore further the common data structures of the array,
list, and stack to gain an understanding of how you might use them in a project.

Reference: Abhishek Sharma 2022, 'Data Structures in C++ | Array | Linked List | Stack', PrepBytes
Blog, accessed 30 January 2024,
<https://www.prepbytes.com/blog/arrays/data-structures-in-c-array-linked-list-stack/>

Section 2: Strategies for Effective Use of Lists and Arrays

source: BoardInfinity

Links to an external site.

Strategies for Using Lists and Arrays Effectively

When navigating lists and arrays, the selection of the right data structure based on
your specific requirements is imperative. But how do you decide on the right one?
Let's look at strategies that can guide you to use these structures most effectively:

● Choosing the Right Data Structure


○ Depending on your operations, be it insertion, deletion, or
retrieval, selecting an appropriate data structure can markedly
enhance efficiency.

○ Example: In a library system, using a list to store a dynamically


changing number of books and an array to manage fixed
categories of genres can be an optimal strategy.
● Efficient Memory Usage
○ Being mindful of your program’s memory consumption is pivotal.
At times, arrays might offer better memory efficiency compared
to lists due to their fixed size.

○ Example: When dealing with a large dataset, considering


memory usage can prevent potential system overloads,
ensuring smooth operation.
● Leveraging Built-in Functions
○ Various programming languages present a large range of
built-in functions that can facilitate smooth operations with lists
and arrays, promoting cleaner code.

○ Example: By familiarising yourself with built-in functions, you


can perform complex operations such as sorting or filtering data
in lists or arrays with minimal code.

Section 3: Case Study: Implementing an Efficient Inventory System at BrightMart

source: freepik
Links to an external site.

Background

BrightMart emerged as a beacon of rapid growth in the retail sector, with a


burgeoning customer base that was continually escalating. To keep pace with the
growing demands and to fortify their market position, the management identified the
need to enhance their inventory management system. The objective was clear: to
overhaul the existing structure and implement a system that would streamline
operations, enhance customer satisfaction, and support sustainable growth. To
achieve this, a strategic decision was made to develop a hybrid system that adeptly
utilises both lists and arrays to manage product information dynamically and
effectively.

Problem Statement

In the initial phase, the management identified a few pressing issues with the current
inventory system:

● Delayed Access to Product Information: The existing system was unable


to provide quick access to product data, causing delays in customer
service.

● Inefficient Inventory Tracking: Inventory levels were not tracked accurately,


leading to overstocking or understocking of products.

● Limited Scalability: The current system couldn’t effectively accommodate


the growing range of products and categories that BrightMart was offering.
Planning and Strategy

To address these issues, a comprehensive plan was crafted.

● Research and Development: A dedicated team was tasked with


researching and developing a state-of-the-art inventory system. This team
spent weeks understanding the nuances of lists and arrays and how they
could be leveraged to create a flexible, scalable, and efficient inventory
system.

● Stakeholder Engagement: A series of workshops were conducted with


various stakeholders, including sales, warehouse management, and IT
personnel, to gather insights and inputs for developing a system that
meets the needs of all stakeholders.

● System Design: Based on the inputs received and the research


conducted, a hybrid system design was conceptualised that would
integrate the versatility of lists with the stability and speed of arrays.

Implementation

The implementation phase saw the translation of planning into action:

● Product Categories with Arrays: Arrays were chosen to manage product


categories. Given their fixed size, arrays allowed for a stable and
structured approach to categorise products. This strategy facilitated rapid
and easy access to different categories, enhancing the efficiency of the
search functionality.

● Individual Product Details with Lists: On the other hand, lists were
employed to manage individual product details within each category. Lists,
with their dynamic size, allowed for seamless addition or removal of
products, offering flexibility in managing the ever-changing inventory
dynamics.
● Training and Deployment: Before full-fledged deployment, staff were
trained to adapt to the new system, followed by a phased rollout to ensure
smooth transition without hindering the daily operations.

Outcome

BrightMart witnessed a transformative change:

● Efficiency Improvement: The new system drastically improved the


efficiency of the inventory management process. Tasks that previously
took hours were now being completed in a fraction of the time, enhancing
productivity across departments.
● Enhanced Customer Satisfaction: The streamlined process meant
customers could now enjoy quicker check-outs and better service, leading
to improved customer satisfaction and loyalty.
● Data-Driven Decision Making: The system facilitated real-time tracking
and reporting of inventory levels, enabling management to make informed,
data-driven decisions, and optimise stock levels effectively.

Topic 2. Stacks and Queues

Key takeaways from this topic...

1. Stacks operate on Last-In-First-Out (LIFO) principles, while queues operate


on First-In-First-Out (FIFO) principles.
2. C++ classes can encapsulate the functionality of these data structures,
providing a clean and reusable codebase.

Learner Guide
The Learner Guide provides the core knowledge for this topic. Work through the
materials and be prepared to discuss these in your forums, tutorials or classes.

Expand All

Panels

Collapse All

Panels

Section 1: Understanding Stacks and Queues

Stacks

In computer science, a stack operates similarly to a physical stack of objects. The


structure follows a Last-In-First-Out (LIFO) approach, meaning the most recently
added item is the first one to be removed. This feature is integral in various
computational scenarios.

● Push: This operation adds an item to the stack, expanding its size. It
places a new item on top of the stack, ready to be the first to be removed
when the time comes.
● Pop: This function removes the top item from the stack, reducing its size.
It facilitates the retrieval and removal of the most recently added item.
● Peek: A utility function that permits viewing of the top item without its
removal, providing a way to know the item at the top without altering the
stack structure.
Learn more about Stack operations

Practical Applications

● Undo Mechanism: In text editors, stacks facilitate the undo functionality,


allowing users to reverse the most recent changes sequentially.
● Backtracking Algorithms: They are also essential in algorithms where
backtracking is necessary to find solutions, such as in maze-solving
algorithms.
Explore practical applications of Stacks

Queues
A queue is analogous to a line of people at a bank, adhering to a First-In-First-Out
(FIFO) principle. This system ensures that the first item added is the first to be
removed, maintaining an order based on the addition time of the elements.

● Enqueue: This method adds an item to the rear of the queue, ensuring the
maintenance of the FIFO structure.
● Dequeue: This method removes an item from the front of the queue,
abiding by the FIFO rule.
● Front: This function allows the viewing of the front item without its
removal, providing insight into the next item to be dequeued without
altering the queue structure.
Learn more about Queue operations

Practical Applications

● Order Processing Systems: Queues manage orders in systems,


processing them in the order they were placed, ensuring fairness and
orderliness.
● Print Queue Management: In networked environments with many users
needing to print documents on a single printer, queues manage the print
jobs in the order they were requested.
Explore practical applications of Queues

Section 2: Case Study - Modernising a Public Transport System

source: RMIT Centre for Urban Research

Background

In an attempt to modernise its public transportation system and enhance the daily
commuting experience of its citizens, the MetroCity local government initiated a
project to integrate technology-driven solutions.

They identified that the incorporation of specific data structures — stacks, queues,
and trees — could play a pivotal role in addressing current inefficiencies and offering
an improved, streamlined service.

Problem Statement

MetroCity was grappling with a congested and disorganised public transport network.
Commuters were often met with irregular bus services, unclear transit routes, and
overcrowded vehicles. Moreover, the existing system lacked a proper method to
gather and utilise data for planning and optimisation. MetroCity needed a
transformative solution to organise and streamline its transport services.
Implementation

To improve the system, MetroCity introduced a digital platform that utilised the
principles of stacks, queues, and trees data structures in the following manner:

● Stacks for Service Maintenance: The corporation implemented a


stack-based system for maintaining and servicing the bus fleet. The buses
were serviced in a LIFO (Last In, First Out) manner, ensuring the buses
that were used more intensively received more frequent maintenance,
thus extending the lifespan of the vehicles.
● Queues for Passenger Management: At bus stops, a queue system was
introduced to manage the passenger influx systematically. This FIFO (First
In, First Out) system ensured a fair and organised way for passengers to
board the buses, reducing chaos and overcrowding.

Outcome

The project significantly improved the efficiency and user-friendliness of MetroCity’s


public transport system. The tree structure offered clear and optimised routes,
reducing travel time and enhancing the commuter experience. The stack and queue
systems ensured well-maintained vehicles and organised boarding processes,
fostering a more civilised and systematic transportation environment.

Topic 3. Linked Lists

Key takeaways from this topic...

1. Linked lists can be singly linked or doubly linked. Singly linked lists contain
pointers to the next node, while doubly linked lists contain pointers to both the
next and previous nodes.
2. Linked lists are dynamic data structures, which means they can easily grow or
shrink during execution.
3. Operations like insertion, deletion, and traversal require an understanding of
pointers and the interconnected nodes to be efficient.

Learner Guide

The Learner Guide provides the core knowledge for this topic. Work through the
materials and be prepared to discuss these in your forums, tutorials or classes.

Expand All

Panels

Collapse All

Panels

Section 1: Introduction to Linked Lists

source: freepik

Links to an external site.


Understanding Linked Lists

In the realm of data structures, a linked list holds a significant place. It is essentially a
linear collection of data elements or nodes, wherein each element points to the next
one, forming a sequence or link.

● Node Structure: Each node in a linked list comprises two components:


the data and a reference to the next node. This structure forms the
backbone of the linked list, ensuring a sequential and dynamic flow of
data.
● Dynamic Structure: The dynamic nature of linked lists offers versatility in
data management. This feature allows for smooth additions or deletions of
elements at different positions, with memory being allocated or
deallocated at runtime, which can be particularly beneficial when dealing
with fluctuating data sizes.

Types of Linked Lists

There are different variations of linked lists, each catering to different needs:

● Singly Linked List: Contains nodes which have a data part and a link to
the next node in the sequence.
● Doubly Linked List: Each node contains, besides the next-node link, a
second link field pointing to the ‘previous’ node in the sequence, which
facilitates traversal in both directions.
● Circular Linked List: The last node in the list points back to the first node,
forming a closed loop.

Further Reading
Understanding the Basics of Linked List

Links to an external site.

Explore the purpose and structure of linked list with visual representations of the
different types.

Reference: Geeks for Geeks n.d., Understanding the Basics of Linked List, Geeks for Geeks,
accessed 30 January 2024, <https://www.geeksforgeeks.org/what-is-linked-list/>

Section 2: Practical Applications of Linked Lists

Memory Allocation

Unlike arrays, linked lists do not allocate a contiguous memory block; instead,
memory is assigned as and when a new node is added. This dynamic memory
allocation can prevent wastage of memory space and offer more flexibility in data
handling.
Insertion and Deletion

In linked lists, the insertion and deletion of nodes are more straightforward
processes. You are not shifting the elements but merely changing the links, which
can be done in constant time, thereby saving computational resources.

Real-World Applications

Linked lists find their application in various real-world scenarios. Here are a few
examples:

● Music Playlists: In music applications, where songs can be added or


removed dynamically.
● Browser Cache: Utilised in browsers to implement forward and backward
navigation of web pages.
● File Management Systems: Employed in operating systems for file storage
and management.

Section 3: Case Study: Enhancing a Social Media Application

source: freepik
Links to an external site.

Background

In the ever-evolving digital landscape, social media platforms stand as bustling hubs
of interaction and content exchange. Imagine a particular platform, let’s call it
‘SocialSphere’, that has witnessed an exponential growth in its user base in recent
years. Initially, the user feed mechanism was based on an array data structure.
However, as the platform expanded, it became increasingly apparent that the
array-based structure was struggling to keep up with the dynamic nature of user
feeds, leading to slower updates and a less responsive user interface.

Preliminary Challenges

The initial system faced significant challenges, mainly revolving around:

● Inefficiency in Data Management: The existing array-based structure


had difficulty accommodating the frequent updates, deletions, and
additions occurring in real-time.
● Scalability Issues: The large volume of users and the consequent data
generated was becoming too great for an array structure to manage
efficiently, leading to scalability issues.
● Delayed Updates: Users started noticing a lag in their feed updates,
which slowed the real-time interaction that is often expected on such
platforms.

Implementation
To overcome these challenges, the development team at SocialSphere embarked on
rethinking their data management strategy. They realised that a doubly linked list
would serve as an ideal solution, as it could handle dynamic data more efficiently.
Here’s how they approached the revamping process:

● Choosing a Doubly Linked List: After a series of deliberations, the team


chose a doubly linked list data structure for its dynamic nature and ease of
inserting or deleting nodes, which would facilitate real-time updates in user
feeds.
● Customising the Data Node: Each node in this list contained not just the
post data, but also links to the previous and next posts, allowing for a
seamless navigation experience.
● Transitioning Data: A critical phase was the migration of existing data to
the new structure without causing any disruption in services.

Testing and Deployment

Before the fully-fledged deployment, rigorous testing was carried out to ensure the
efficiency and reliability of the new system. The development team created
simulations to test the performance of the new structure under different loads and
conditions.

Outcome

Post-implementation, the changes were significant:

● Enhanced User Engagement: The user engagement levels surged, with


users finding their feed more responsive and constantly updated with fresh
content.
● Scalable Infrastructure: The new data structure allowed the platform to
efficiently handle the increasing data volume, showcasing excellent
scalability prospects.
● Positive User Feedback: Users appreciated the improvements, resulting
in positive reviews and an enhanced platform reputation.
Further Resources
The resources in this section are for further exploration, providing additional
information for deeper insights.

Expand All
Panels
Collapse All
Panels
Reading: Linked List Data Structure In C++
A linked list is a linear dynamic data structure to store data items. This article gives
further explanation of this data structure and demonstrates various operations that
can be performed on linked list with code examples.

Linked List Data Structure In C++

Links to an external site.

Reference: (2023) 'Linked List Data Structure In C++', Software Testing Help, accessed 30 January
2024, <https://www.softwaretestinghelp.com/linked-list/>

Reading: Data Structures in C++ - Array | Linked List | Stack


Depending on your project requirements, it is important to choose the right data
structure for your project. This article explores further the common data structures of
the array, list, and stack to gain an understanding of how you might use them in a
project.

Data Structures in C++ - Array | Linked List | Stack

Links to an external site.

Reference: Sharma, A. (2022) 'Data Structures in C++ | Array | Linked List | Stack', PrepBytes Blog,
accessed 16 Sept. 2024,
<https://www.prepbytes.com/blog/arrays/data-structures-in-c-array-linked-list-stack/>

You might also like