Creating a Simple Custom List in C++

ANC Programs
2 min readNov 5, 2023

--

#include <iostream>

class CustomList
{
struct Node
{
Node *next;
int data;
Node(int item): data(item), next(nullptr){}
};
Node *head;

public:
CustomList(): head(nullptr) {}
~CustomList(){
while(head)
{
Node *temp = head;
head = head->next;
delete temp;
}
}

void push_back(int item)
{
Node *newNode = new Node(item);

if(!head)
{
head = newNode;
}else
{
Node *current = head;
while(current->next)
{
current = current->next;
}
current->next = newNode;
}
}

void print()
{
if(head)
{
Node *current = head;
while(current)
{
std::cout<<current->data<<"\n";
current = current->next;
}
}
}
};

int main()
{
CustomList clist;
clist.push_back(10);
clist.push_back(100);
clist.print();
return 0;
}

Explanation

  • This C++ program demonstrates how to create a simple custom list class.
  • The CustomList class includes a private inner Node struct, which represents individual elements in the list.
  • The list is implemented as a singly-linked list with a head pointer.
  • The push_back method appends a new item to the end of the list.
  • The print method displays the list elements.
  • In the main function, a CustomList object is created, items are added to the list, and then the list is printed.

In a previous post, I explained how to create custom vectors in C++. Vectors are like dynamic arrays with fast access, and they can hold elements of a specific data type (e.g., int, double). Lists, on the other hand, can do efficient insertions/removals, and they can also store elements of different data types. Vectors offer contiguous memory and automatic management, while lists have higher memory overhead and aren’t contiguous. Choose vectors for speed and stability, lists for frequent changes when working with specific data types.

--

--

ANC Programs

Learning skilled programs like C++, Java, Docker and many more