element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • About Us
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Code Exchange
  • Technologies
  • More
Code Exchange
Blog C++ Tutorial - Linked List Operations
  • Blog
  • Forum
  • Documents
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Code Exchange to participate - click to join for free!
  • Share
  • More
  • Cancel
Group Actions
  • Group RSS
  • More
  • Cancel
Engagement
  • Author Author: oneleggedredcow
  • Date Created: 3 Apr 2013 2:07 AM Date Created
  • Views 1157 views
  • Likes 0 likes
  • Comments 0 comments
  • code_exchange
  • Code Exchange
  • programming
  • raspberry_pi
  • code
  • rpi
  • c++
  • learnc++
Related
Recommended

C++ Tutorial - Linked List Operations

oneleggedredcow
oneleggedredcow
3 Apr 2013

Introduction

In this previous tutorial, we learned about linked lists. Linked list are a way to store data when you don’t know how many items you are going to have until you are done. A simple example would be finding all of the letters in a text file that start with the letter a.  We also discussed some of the performance implications of a linked list versus an array.

 

In this tutorial, we are going to implement some common operations that would be performed on a linked list like adding an element to the end, inserting an element in the middle of the list, and removing an element from the list.

Code

So, the first thing that I’m going to do is declare a class to store and manage my linked list:

 

class LinkedList

{

public:

LinkedListItem* Head;

 

LinkedList();

};


LinkedList::LinkedList()

{

Head = NULL;

}

 

This way, I can group all of my methods that deal with the linked list together in a logical place. So, the first method that we are going to put on the class is a way to print out the contents of the list:

 

void LinkedList::Print()

{

LinkedListItem* curr = Head;

while(curr != NULL)

{

cout << curr->Number << endl;

curr = curr->Next;

}

}


This is a great first method to write, since it will give us a way to debug the rest of the methods. Next, we’ll add a way to add elements to the list.  As a slight optimization, I’m going to also add a variable on the class that stores the end of the list, as well as the beginning:

 

class LinkedList

{

public:

LinkedListItem* Head;

LinkedListItem* End;

 

LinkedList();

 

void Print();

 

void Add(int number);

};


void LinkedList::Add(int number)

{

LinkedListItem* item = new LinkedListItem(number);

if(Head == NULL)

{

Head = item;

End = item;

}

else

{

End->Next = item;

End = End->Next;

}

}


This should be pretty straight forward.  The only thing to watch out for is that when we first create the list, the Head variable will be NULL, so if it is the first item in the list, we need to update the Head variable.

 

Now, let’s write a function to grab an item at a random index in the linked list:

 

LinkedListItem* LinkedList::ElementAt(int index)

{

int idx = 0;

LinkedListItem* curr = Head;

while(curr != NULL && idx < index)

{

curr = curr->Next;

idx++;

}

 

if(idx != index)

{

curr = NULL;

}

 

return curr;

}


If you remember the performance discussion from the previous tutorial, this is why accessing random elements in a linked list is slower than an array.

This method also brings up an interesting question of what should we do if the index that is requested doesn’t exist?  There are many ways to solve this problem, but in this case we return a NULL pointer. This is a good indication to the user that something went wrong.

 

Now, using that function, we can write a function to insert an element in a random location:

 

bool LinkedList::Insert(int index, int number)

{

LinkedListItem* item = new LinkedListItem(number);

 

if(index == 0)

{

LinkedListItem* tmp = Head;

Head = item;

item->Next = tmp;

 

if(End == NULL)

{

End = item;

}

 

return true;

}

else

{

LinkedListItem* prev = ElementAt(index - 1);

if(prev != NULL)

{

LinkedListItem* tmp = prev->Next;

prev->Next = item;

item->Next = tmp;

 

if(prev == End)

{

End = item;

}

 

return true;

}

 

return false;

}

}


The easiest way to understand this function is to start with thinking about the case where we need to insert an element in the middle of the list.  In this case, we need to update the element before it’s Next variable to point to the element that we are inserting, and we need to update the element that we are inserting’s Next variable to point to the element that the previous element’s Next variable used to point to.  That’s the tricky part, the rest is just minor bookkeeping.

 

The other thing to note about the method is that it returns whether or not the operation succeeded. This is important because the insert can fail if the caller requests an index that is less than zero or greater than the length of the list, and it is critical to let the caller know if the operation was successful.

 

Now we need to consider removing elements from the list, making sure to clean up any memory that was allocated to store them.  The first thing that we will implement is removing all of the items from the list:

 

void LinkedList::Clear()

{

LinkedListItem* curr = Head;

while(curr != NULL)

{

LinkedListItem* tmp = curr;

curr = curr->Next;

delete tmp;

}

 

Head = NULL;

End = NULL;

}


Clearing the list is pretty straight-forward.  The only thing to remember is to call delete on the item that we remove!  Next is removing an item from the list.  This is the reverse of the insert case above, so we need to make sure that the Next pointers are all correct after we are done:

 

bool LinkedList::Remove(int number)

{

LinkedListItem* prev = NULL;

LinkedListItem* curr = Head;

while(curr != NULL)

{

if(curr->Number == number)

{

if(prev == NULL)

{

Head = curr->Next;

 

if(End == curr)

{

End = NULL;

}

 

delete curr;

}

else

{

prev->Next = curr->Next;

 

if(End == curr)

{

End = prev;

}

 

delete curr;

}

 

return true;

}

 

prev = curr;

curr = curr->Next;

}

 

return false;

}


This removes the first occurrence of the number that was passed in, and does nothing if the number that is passed in does not exist in the list.  Another way to remove an item from the list would be to remove the item at a given index.

 

The last thing that we are going to do is put a call to Clear in the destructor:

 

LinkedList::~LinkedList()

{

Clear();

}


This will ensure that the memory will be cleaned up properly when the list the deleted.

Summary

In this tutorial, we implemented some of the common operations that can be done on linked lists. Hopefully doing this illustrated some of the benefits and weaknesses of linked lists that we mentioned in the previous tutorial.

 

In the next tutorial, we will be going over the STL linked list.  Since linked lists are so common, there is a standard implementation that you can use for your projects.  This saves you the time (and tracking down the bugs) associated with writing your own. However, even if you do use a standard implementation, it is still very important to understand what is going on under the covers.  This will help you know whether or not it is the correct fit for what you are trying to accomplish.

 

If you have any questions or comments about what was covered here, post them to the comments.  I watch them closely and will respond and try to help you out.

Tutorial Index

01 - Hello Raspberry Pi

02 - Reading User Input

03 - If Statement

04 - For Loops

05 - While Loops

06 - Functions

07 - Data Types

08 - Arrays

09 - Structures

10 - Classes

11 - Pointers

12 - Dynamic Arrays

13 - Linked List

14 - Linked List Operations

15 - STL List/Vector

16 - Templates

17 - Inheritance

18 - File I/O

19 - Strings

20 - Constants

21 - Hash Tables

  • Sign in to reply
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube