BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

C++ Tutorial - Linked List Basics - 2020

cplusplus_icon.png




Bookmark and Share





bogotobogo.com site search:




Linked Lists

A linked list is a basic data structure where each item contains the information that we need to get to the next item.

The main advantage of linked lists over arrays is that the links provide us with the capability to rearrange the item efficiently. This flexibility is gained at the expense of quick access to any arbitrary item in the list, because the only way to access to an item in the list is to follow links from the beginning.



struct vs class - list element

We can make linked list either as a struct or a class as shown below:

struct list_element
{
  list_element(int n = 0, list_element* ptr = 0):
    data(n), next(ptr) {};
  int data;
  list_element *next;
};

class list_element
{
public:
  list_element(int n = 0, list_element* ptr = 0):
    data(n), next(ptr) {};
  int data;
  list_element* next;
}

Both of the codes are equivalent.
We have two data members (data and next) and a constructor with initialization list. All of the members are public.




list class

Here is the code for list class with the list element struct:

struct list_element
{
  list_element(int n = 0, list_element* ptr = 0):
    data(n), next(ptr) {};
  int data;
  list_element *next;
};

class list
{
public:
  list(list_element *h = 0, list_element *c = 0):head(h),cursor(c) {}
  void prepend(int n);  // add an element before head
  void add(int n);   // add an element at the end of the list
  int get_element() { return cursor->data;}
  void advance() { cursor = cursor->next; }
  void print();
private:
  list_element *head;
  list_element *cursor;
};

The class has 6 methods:

  1. list() - constructor with initialization list for head and cursor pointing to the current element.
  2. prepend() - to insert a list element before the given element.
  3. add() - to append a list element at the end of the list.
  4. get_element() - to return the current data.
  5. advance() - to move the cursor to the next list element.
  6. print() - to print list elements.

The list class two private members:

  1. head - pointer to the first list_element.
  2. cursor - pointer to the current list_element.



linked list code

Here is the implementation of the singly linked list:

#include <iostream>
using namespace std;

typedef struct list_element
{
  list_element(int n = 0, list_element* ptr = 0):
    data(n), next(ptr) {};
  int data;
  list_element *next;
} list_element;

class list
{
public:
  list(list_element *h = 0, list_element *c = 0):head(h),cursor(c) {}
  void prepend(int n);  // add an element before head
  void add(int n);   // add an element at the end of the list
  int get_element() { return cursor->data;}
  void advance() { cursor = cursor->next; }
  void print();
private:
  list_element *head;
  list_element *cursor;
};

void list::prepend(int n)
{
  // swap head with current head
  if(head) {
    head = cursor = new list_element(n, head);
  }
  // if empty list, make current element as head
  else
    head = new list_element(n, head);
}

void list::add(int n)
{
  if(head) {
    cursor = head;
    while(cursor) {
      // end of the list
      if(cursor->next == NULL) {
        cursor->next = new list_element(n);
        break;
      }
      // advance to the next element
      else
        advance();
    }
  }
  // no head, make head with current element
  else {
    head = new list_element(n);
  }
}

void list::print()
{
  if(head)
  {
    cursor = head;
    while(cursor) {
      cout << get_element() << " ";
      advance();
    }
  }
  else
    cout << "Empty list!" << endl;
}

int main()
{
  list myList(new list_element(1));
  myList.add(2);
  myList.add(3);
  myList.prepend(0);
  myList.add(4);
  myList.prepend(-1);
  myList.add(5);
  myList.print();
  return 0;
}

Output:

-1 0 1 2 3 4 5



linked list code 2

For more complete implementation, we need a descturtor. Also, for convenience, we may want to construct the list from an array. Here is a new code with those two member functions:

#include <iostream>
using namespace std;

typedef struct list_element
{
  list_element(int n = 0, list_element* ptr = 0):
    data(n), next(ptr) {};
  int data;
  list_element *next;
} list_element;


class list
{
public:
  list(list_element *h = 0, list_element *c = 0):head(h),cursor(c)
  { cout << "default constructor\n"; }

  list(const int *arr, int sz); // move elements from an array
  ~list(); // destructor

  void prepend(int n);  // add an element before head
  void add(int n);   // add an element at the end of the list
  int get_element() { return cursor->data;}
  void advance() { cursor = cursor->next; }
  void print();
private:
  list_element *head;
  list_element *cursor;
};

// constructor : move elements from an array
list::list(const int array[], int sz)
{
  head = cursor = 0;

  // populate the list element using add()
  for(int i = 0; i < sz; ++i) {
    add(array[i]);
  }
}

// destructor
list::~list()
{
  for(cursor = head; cursor != 0;) {
    cursor = head->next;
    delete head;
    head = cursor;
  }
}

void list::prepend(int n)
{
  // swap head with current head
  if(head) {
    head = cursor = new list_element(n, head);
  }
  // if empty list, make current element as head
  else
    head = new list_element(n, head);
}

void list::add(int n)
{
  if(head) {
    cursor = head;
    while(cursor) {
      // end of the list
      if(cursor->next == NULL) {
        cursor->next = new list_element(n);
        break;
      }
      // advance to the next element
      else
        advance();
    }
  }
  // no head, make head with current element
  else {
    head = new list_element(n);
  }
}

void list::print()
{
  if(head)
  {
    cursor = head;
    while(cursor) {
      cout << get_element() << " ";
      advance();
    }
  }
  else
    cout << "Empty list!" << endl;
}

int main()
{
  int arr[] = {1, 2, 3, 4, 5};
  list myList(arr,5);
  myList.add(6);
  myList.prepend(0);
  myList.print();
  return 0;
}

Output:

0 1 2 3 4 5 6



Other linked list sample codes

There are more sample codes for linked list:

  1. Linked List Examples
  2. Linked List - Quiz







Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






C++ Tutorials

C++ Home

Algorithms & Data Structures in C++ ...

Application (UI) - using Windows Forms (Visual Studio 2013/2012)

auto_ptr

Binary Tree Example Code

Blackjack with Qt

Boost - shared_ptr, weak_ptr, mpl, lambda, etc.

Boost.Asio (Socket Programming - Asynchronous TCP/IP)...

Classes and Structs

Constructor

C++11(C++0x): rvalue references, move constructor, and lambda, etc.

C++ API Testing

C++ Keywords - const, volatile, etc.

Debugging Crash & Memory Leak

Design Patterns in C++ ...

Dynamic Cast Operator

Eclipse CDT / JNI (Java Native Interface) / MinGW

Embedded Systems Programming I - Introduction

Embedded Systems Programming II - gcc ARM Toolchain and Simple Code on Ubuntu and Fedora

Embedded Systems Programming III - Eclipse CDT Plugin for gcc ARM Toolchain

Exceptions

Friend Functions and Friend Classes

fstream: input & output

Function Overloading

Functors (Function Objects) I - Introduction

Functors (Function Objects) II - Converting function to functor

Functors (Function Objects) - General



Git and GitHub Express...

GTest (Google Unit Test) with Visual Studio 2012

Inheritance & Virtual Inheritance (multiple inheritance)

Libraries - Static, Shared (Dynamic)

Linked List Basics

Linked List Examples

make & CMake

make (gnu)

Memory Allocation

Multi-Threaded Programming - Terminology - Semaphore, Mutex, Priority Inversion etc.

Multi-Threaded Programming II - Native Thread for Win32 (A)

Multi-Threaded Programming II - Native Thread for Win32 (B)

Multi-Threaded Programming II - Native Thread for Win32 (C)

Multi-Threaded Programming II - C++ Thread for Win32

Multi-Threaded Programming III - C/C++ Class Thread for Pthreads

MultiThreading/Parallel Programming - IPC

Multi-Threaded Programming with C++11 Part A (start, join(), detach(), and ownership)

Multi-Threaded Programming with C++11 Part B (Sharing Data - mutex, and race conditions, and deadlock)

Multithread Debugging

Object Returning

Object Slicing and Virtual Table

OpenCV with C++

Operator Overloading I

Operator Overloading II - self assignment

Pass by Value vs. Pass by Reference

Pointers

Pointers II - void pointers & arrays

Pointers III - pointer to function & multi-dimensional arrays

Preprocessor - Macro

Private Inheritance

Python & C++ with SIP

(Pseudo)-random numbers in C++

References for Built-in Types

Socket - Server & Client

Socket - Server & Client 2

Socket - Server & Client 3

Socket - Server & Client with Qt (Asynchronous / Multithreading / ThreadPool etc.)

Stack Unwinding

Standard Template Library (STL) I - Vector & List

Standard Template Library (STL) II - Maps

Standard Template Library (STL) II - unordered_map

Standard Template Library (STL) II - Sets

Standard Template Library (STL) III - Iterators

Standard Template Library (STL) IV - Algorithms

Standard Template Library (STL) V - Function Objects

Static Variables and Static Class Members

String

String II - sstream etc.

Taste of Assembly

Templates

Template Specialization

Template Specialization - Traits

Template Implementation & Compiler (.h or .cpp?)

The this Pointer

Type Cast Operators

Upcasting and Downcasting

Virtual Destructor & boost::shared_ptr

Virtual Functions



Programming Questions and Solutions ↓

Strings and Arrays

Linked List

Recursion

Bit Manipulation

Small Programs (string, memory functions etc.)

Math & Probability

Multithreading

140 Questions by Google



Qt 5 EXPRESS...

Win32 DLL ...

Articles On C++

What's new in C++11...

C++11 Threads EXPRESS...

Go Tutorial

OpenCV...








Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master