Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
C++ Data Structures and Algorithms
C++ Data Structures and Algorithms

C++ Data Structures and Algorithms: Learn how to write efficient code to build scalable and robust applications in C++

Arrow left icon
Profile Icon Wisnu Anggoro
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (5 Ratings)
Paperback Apr 2018 322 pages 1st Edition
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Wisnu Anggoro
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (5 Ratings)
Paperback Apr 2018 322 pages 1st Edition
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

C++ Data Structures and Algorithms

Storing Data in Lists and Linked Lists

In the previous chapter, we discussed basic C++ programming, so that now we can build a program and run it. We also tried to find out the complexity of the code flow using algorithm analysis. In this chapter, we are going to learn about building the list and linked list data structures and find out the complexity of each data structure. To understand all of the concepts in these data structures, these are the topics we are going to discuss:

  • Understanding the array data type and how to use it
  • Building the list data structure using the array data type
  • Understanding the concept of node and node chaining
  • Building SinglyLinkedList and DoublyLinkedList using node chaining
  • Applying the Standard Template Library to implement the list and linked list

Technical requirements

To follow along with this chapter including the source code, we require the following:

Getting closer to an array

An array is a series of elements with the same data type that is placed in contiguous memory locations. This means that the memory allocation is assigned in consecutive memory blocks. Since it implements contiguous memory locations, the elements of the array can be individually accessed by the index. Let's take a look at the following array illustration:

As we can see in the preceding illustration, we have an array containing five elements. Since the array uses zero-based indexing, the index starts from 0. This index is used to access the element value and to also replace the element value. The memory address stated in the illustration is for example purposes only. In reality, the memory address might be different. However, it illustrates that the memory allocation is contiguous. 

Now, if we want to create the preceding array in C++,...

Building a List ADT

A list is a sequence of items with similar data types, where the order of the item's position matters. There are several common operations that are available in a List ADT, and they are:

  • Get(i), which will return the value of selected index, i. If the i index is out of bounds, it will simply return -1.
  • Insert(i, v), which will insert the v value at the position of index i.
  • Search(v), which will return the index of the first occurrence of v (if the v value doesn't exist, the return value is -1).
  • Remove(i), which will remove the item in the i index. 
For simplicity, we are going to build a List ADT that accepts int data only, from zero (0) and higher. 

Now, by using the array data type we discussed earlier, let's build a new...

Introduction to node

The node is the basic building block of many data structures which we will discuss in this book. Node has two functions. Its first function is that it holds a piece of data, also known as the Value of node. The second function is its connectivity between another node and itself, using an object reference pointer, also known as the Next pointer. Based on this explanation, we can create a Node data type in C++, as follows:

class Node
{
public:
int Value;
Node * Next;
};

We will also use the following diagram to represent a single node:

Now, let's create three single nodes using our new Node data type. The nodes will contain the values 7, 14, and 21 for each node. The code should be as follows:

Node * node1 = new Node;
node1->Value = 7;

Node * node2 = new Node;
node2->Value = 14;

Node * node3 = new Node;
node3->Value = 21;

Note...

Building a Singly Linked List ADT

The Singly Linked List (also known as the linked list) is a sequence of items linked with each other. It's actually a chaining of nodes, where each node contains the item's value and the next pointer. In other words, each item in the linked list has a link to its next item in the sequence. The thing that differs between the linked list and the node chain is that the linked list has a Head and a Tail pointer. The Head informs the first item and the Tail informs the last item in the linked list. Similar to the List ADT, we discussed earlier, the linked list has Get(), Insert(), Search(), and Remove() operations, where all of the operations have the same functionality compared to List. However, since we now have Head and Tail pointers, we will also create others operations, and these are InsertHead(), InsertTail...

Building the Doubly Linked List ADT

The Doubly Linked List is almost the same as the Singly Linked List, except the Node used by Doubly Linked List has a Previous pointer instead of only having the Next pointer. The existence of the Previous pointer will make the Doubly Linked List possible to move backwards from Tail to Head. As a result, we can reduce the complexity of the RemoveTail() operation to O(1) instead of O(N), like we have in the Singly Linked List data type. We are going to discuss this further later in this section. As of now, let's prepare the new Node data type.

Refactoring the Node<T> data type

Before we build a Doubly Linked List, we need to add a Previous pointer...

Applying List and LinkedList using STL

C++ has three data types which we can use to store specific items such as List, SinglyLinkedList, and DoublyLinkedList. std::vector can be used as List , std::forward_list can be used as SinglyLinkedList, and std::list can be used as DoublyLinkedList. They both have fetching, inserting, searching, and removing operations. However, the method names they have are different with our developed data type, and we are going to discuss this in this section. In this section, we are going to discuss std::vector and std::list only, since std::forward_list is similar to std:: list.

std::vector

A vector, which is like an array, is a container to store a bunch of items contiguously...

Technical requirements


To follow along with this chapter including the source code, we require the following:

Getting closer to an array


An array is a series of elements with the same data type that is placed in contiguous memory locations. This means that the memory allocation is assigned in consecutive memory blocks. Since it implements contiguous memory locations, the elements of the array can be individually accessed by the index. Let's take a look at the following array illustration:

As we can see in the preceding illustration, we have an array containing five elements. Since the array uses zero-based indexing, the index starts from 0. This index is used to access the element value and to also replace the element value. The memory address stated in the illustration is for example purposes only. In reality, the memory address might be different. However, it illustrates that the memory allocation is contiguous. 

Now, if we want to create the preceding array in C++, here is the code:

// Project: Array.cbp
// File   : Array.cpp

#include <iostream>

using namespace std;

int main()
{
    //...

Building a List ADT


list is a sequence of items with similar data types, where the order of the item's position matters.There are several common operations that are available in a List ADT, and they are:

  • Get(i), which will return the value of selected index, i. If the i index is out of bounds, it will simply return -1.
  • Insert(i, v), which will insert the v value at the position of index i.
  • Search(v), which will return the index of the first occurrence of v (if the v value doesn't exist, the return value is -1).
  • Remove(i), which will remove the item in the i index. 

Note

For simplicity, we are going to build a List ADT that accepts int data only, from zero (0) and higher. 

Now, by using the array data type we discussed earlier, let's build a new ADT named List which contains the preceding operations. We need two variables to hold the list of items (m_items) and the number of items in the list (m_count). We will make them private so that it cannot be accessed from the outside class. All four operations...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • • Use data structures such as arrays, stacks, trees, lists, and graphs with real-world examples
  • • Learn the functional and reactive implementations of the traditional data structures
  • • Explore illustrations to present data structures and algorithms, as well as their analysis, in a clear, visual manner

Description

C++ is a general-purpose programming language which has evolved over the years and is used to develop software for many different sectors. This book will be your companion as it takes you through implementing classic data structures and algorithms to help you get up and running as a confident C++ programmer. We begin with an introduction to C++ data structures and algorithms while also covering essential language constructs. Next, we will see how to store data using linked lists, arrays, stacks, and queues. Then, we will learn how to implement different sorting algorithms, such as quick sort and heap sort. Along with these, we will dive into searching algorithms such as linear search, binary search and more. Our next mission will be to attain high performance by implementing algorithms to string datatypes and implementing hash structures in algorithm design. We'll also analyze Brute Force algorithms, Greedy algorithms, and more. By the end of the book, you'll know how to build components that are easy to understand, debug, and use in different applications.

Who is this book for?

This book is for developers who would like to learn the Data Structures and Algorithms in C++. Basic C++ programming knowledge is expected.

What you will learn

  • • Know how to use arrays and lists to get better results in complex scenarios
  • • Build enhanced applications by using hashtables, dictionaries, and sets
  • • Implement searching algorithms such as linear search, binary search, jump search, exponential search, and more
  • • Have a positive impact on the efficiency of applications with tree traversal
  • • Explore the design used in sorting algorithms like Heap sort, Quick sort, Merge sort and Radix sort
  • • Implement various common algorithms in string data types
  • • Find out how to design an algorithm for a specific task using the common algorithm paradigms

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 26, 2018
Length: 322 pages
Edition : 1st
Language : English
ISBN-13 : 9781788835213
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Apr 26, 2018
Length: 322 pages
Edition : 1st
Language : English
ISBN-13 : 9781788835213
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 136.97
The Modern C++ Challenge
$38.99
C++ Data Structures and Algorithms
$48.99
C++ High Performance
$48.99
Total $ 136.97 Stars icon
Banner background image

Table of Contents

10 Chapters
Learning Data Structures and Algorithms in C++ Chevron down icon Chevron up icon
Storing Data in Lists and Linked Lists Chevron down icon Chevron up icon
Constructing Stacks and Queues Chevron down icon Chevron up icon
Arranging Data Elements Using a Sorting Algorithm Chevron down icon Chevron up icon
Finding out an Element Using Searching Algorithms Chevron down icon Chevron up icon
Dealing with the String Data Type Chevron down icon Chevron up icon
Building a Hierarchical Tree Structure Chevron down icon Chevron up icon
Associating a Value to a Key in a Hash Table Chevron down icon Chevron up icon
Implementation of Algorithms in Real Life Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
(5 Ratings)
5 star 20%
4 star 20%
3 star 20%
2 star 20%
1 star 20%
Giovanny Ortegon Feb 05, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Feefo Verified review Feefo
Bill P Dec 10, 2018
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This book looks good. Not a very thick book, but the author provides some interesting material. Note, my review is based on my initial glance through the book. I have not tried any of the algorithms and cannot vouch just yet for their correctness. Things look about right.
Amazon Verified review Amazon
Mutombo Matanda Hervé Feb 16, 2020
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
I would have liked more explanations and perhaps narrations than there currently are in the book. It was more of a : A constant is something that stays the same, here's example one... Now let's move on to the next chapter.
Amazon Verified review Amazon
Anthony Das Nov 12, 2018
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
Although I’ve learnt about various data structures over the years as a professional programmer, I’ve never had a formal education into them and wanted a text to solidify and expand my knowledge. Early on, however, you pick up that the author’s first language isn’t English. His sentences can be ambiguous and some only made sense because I already had some area knowledge with which I could piece together what was meant. This is very different to other programming texts I’ve read that have quite a precise way with words.The same lack of quality also pervaded the code. Although the code does adequately demonstrate the underlying mechanics fairly well, it’s very rough and “non-production”. Eg.:- C++98 use of naked pointers via new. Ok, so we don’t want to use smart pointers, but there’s not a single use of delete. Hence, there are memory leaks throughout.- “Animal dog = Animal();” Strange style.- void LinkedList<T>::RemoveHead(){…} forgets to update the Tail pointer if there was only one element (i.e. Head and Tail are the same element). Same thing in void DoublyLinkedList<T>::RemoveHead(){…}.- Builds an AVL tree class inheriting from base BST but doesn’t make overridden functions virtual within base.There are also times when the author doesn’t quite seem to understand what’s going on:- “To search for the desired element, we can use find() method provided by the vector.” But code then uses <algorithm> find(), there is no vector::find().- Conversely, “We can use the erase() method provided by the vector. To use this method, we also need to include the algorithm header.” He then correctly employs vector::erase() without needing <algorithm>.Chapter 9 is incomplete both in terms of content (“We will now show”… but then the section abruptly ends) and in terms of presentation (e.g. the font will randomly change in places). There’s a brief introduction for a linear congruential generator but with a = 1 and m = 10. Why couldn’t some proper values be used instead?I could go on but I’ve made my point. I did learn how to balance a binary search tree and a new sorting algorithm (radix), so the text did expand my knowledge. I also commend the author for at least trying to produce a text and help the community. But overall, I wouldn’t recommend as there are surely better texts out there. Even putting aside the monetary cost of the text, you will waste time trying to understand the author's use of English.
Amazon Verified review Amazon
Amazon Customer Oct 01, 2022
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
This book unconventional syntax such as its for loops that get in the way of understanding concepts like linked lists. I did not find the material helpful for me to understand how to use linked lists.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.