C++ - Linked Lists in C++ 1 (Singly Linked List)
C++ - Linked Lists in C++ 1 (Singly Linked List)
Certificate of Completion
We're Hiring
Campus
Ambassadors
Register
(https://forms.gle/YWUXdKkZ7pbaX8Wr5)
https://www.codesdope.com/blog/article/c-linked-lists-in-c-singly-linked-list/ 2/15
11/10/22, 6:35 AM C++ : Linked lists in C++ (Singly linked list)
Notice that the last node doesn’t point to any other node
and just stores NULL.
struct node
{
int data;
struct node *next;
};
https://www.codesdope.com/blog/article/c-linked-lists-in-c-singly-linked-list/ 3/15
11/10/22, 6:35 AM C++ : Linked lists in C++ (Singly linked list)
You are now clear with the concepts of a linked list. Let’s
code it up. The first part is to create a node (structure).
https://www.codesdope.com/blog/article/c-linked-lists-in-c-singly-linked-list/ 4/15
11/10/22, 6:35 AM C++ : Linked lists in C++ (Singly linked list)
#include <iostream>
struct node
{
int data;
node *next;
};
#include <iostream>
struct node
{
int data;
node *next;
};
class linked_list
{
private:
node *head,*tail;
public:
linked_list()
{
head = NULL;
tail = NULL;
}
};
int main()
{
linked_list a;
return 0;
}
We have made two nodes – head and tail. We will store the
first node in ‘head’ and the last node in ‘tail’. The
constructor of the linked list is making both ‘head ’ and ‘
https://www.codesdope.com/blog/article/c-linked-lists-in-c-singly-linked-list/ 5/15
11/10/22, 6:35 AM C++ : Linked lists in C++ (Singly linked list)
#include <iostream>
struct node
{
int data;
node *next;
};
class linked_list
{
private:
node *head,*tail;
public:
linked_list()
{
head = NULL;
tail = NULL;
}
void add_node(int n)
{
node *tmp = new node;
tmp->data = n;
tmp->next = NULL;
if(head == NULL)
{
head = tmp;
tail = tmp;
}
else
{
tail->next = tmp;
tail = tail->next;
}
}
};
int main()
{
linked_list a;
a.add_node(1);
a.add_node(2);
return 0;
}
https://www.codesdope.com/blog/article/c-linked-lists-in-c-singly-linked-list/ 6/15
11/10/22, 6:35 AM C++ : Linked lists in C++ (Singly linked list)
If you are not familiar with the ‘malloc’ function, then just
read the dynamic memory allocation chapter
(https://www.codesdope.com/cpp-dynamic-memory/).
if(head == NULL)
head = tmp;
tail = tmp;
else
tail->next = tmp;
tail = tail->next;
}
https://www.codesdope.com/blog/article/c-linked-lists-in-c-singly-linked-list/ 7/15
11/10/22, 6:35 AM C++ : Linked lists in C++ (Singly linked list)
The new node (tmp) will go after the ‘tail’ and then we are
changing the tail because the new node is the new ‘tail’.
Next:
1. Linked list traversal using while loop and recursion
(https://www.codesdope.com/blog/article/linked-list-
traversal-using-loop-and-recursion-in-/)
https://www.codesdope.com/blog/article/c-linked-lists-in-c-singly-linked-list/ 8/15