C++ Linked List Data Structure
C++ Linked List Data Structure
In this tutorial, you will learn about linked list data structure and it's
implementation in Python, Java, C, and C++.
Linked lists can be of multiple types: singly, doubly, and circular linked
list. In this article, we will focus on the singly linked list.
Note: You might have played the game Treasure Hunt, where each clue
includes the information about the next clue. That is how the linked list
operates.
• A data item
We wrap both the data item and the next node reference in a struct as:
struct node
{
int data;
struct node *next;
};
Each struct node has a data item and a pointer to another struct node. Let
us create a simple Linked List with three items to understand how this
works.
/* Initialize nodes */
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;
/* Allocate memory */
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
/* Connect nodes */
one->next = two;
two->next = three;
three->next = NULL;
If you didn't understand any of the lines above, all you need is a refresher
on pointers and structs.
In just a few steps, we have created a simple linked list with three nodes.
• Point its next pointer to the struct node containing 2 as the data value
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
// Creating a node
class Node {
public:
int value;
Node* next;
};
int main() {
Node* head;
Node* one = NULL;
Node* two = NULL;
Node* three = NULL;
// Connect nodes
one->next = two;
two->next = three;