How to implement a linked list in C++?

#15
by osanseviero HF staff - opened

Question:

How to implement a linked list in C++?

Answer:

There are a few implementations of linked lists on the internet, most of which are rather outdated. Here’s one that’s not too bad.

Here’s a fairly straightforward implementation of a doubly-linked list in C++:

#include <iostream>
#include <string>
#include <cstdlib>
#include <cstddef>
#include <cstdint>
#include <list>
#include <vector>

struct ListNode {
int data;
struct ListNode *next;
struct ListNode *prev;
};

ListNode *createListNode(int data) {
ListNode *newNode = new ListNode();
newNode->data = data;
newNode->next = NULL;
newNode->prev = NULL;
return newNode;
}

ListNode *createListNode(int data, int left, int right) {
ListNode *newNode = createListNode(data);
newNode->next = createListNode(left);

if(left!= right)
    newNode-&gt;next-&gt;prev = newNode;
else
    newNode-&gt;next = createListNode(right);
newNode-&gt;next-&gt;prev = newNode;
return newNode;

}

void printListNode(ListNode *node) {
if(node)
std::cout << node->data << " -> ";
else
std::cout << "NULL";
}

void printList(ListNode *node) {
while(node)
printListNode(node);
}

void printList(ListNode *node) {
printList(node->next);
printListNode(node);
printList(node->prev);
}

void printList(ListNode *node) {
if(node)
printList(node->next);
else
std::cout << "NULL";
}

int main() {
ListNode *head = createListNode(1);
head = createListNode(2, head);
head = createListNode(3, head);

Sign up or log in to comment