You are on page 1of 6

Doubly Linked List:

A doubly linked list is a type of linked list where each node has pointers to both the next and the
previous nodes.

1. Insertion at the End (Append):

 Create a new node with the given data.


 Make the last node's "next" point to the new node, and the new node's "prev" point to the last
node.
 Update the "tail" pointer to the new node if needed.

2. Display:

 Traverse the list from the "head" node to the "tail" node, printing each node's data.

C++ code:
#include <iostream>

class Node {

public:

int data;

Node* next; // pointer for the next node

Node* prev; // pointer of the previous node

Node(int value) {

data = value;

next = nullptr;

prev = nullptr;

};
class DoublyLinkedList {

private:

Node* head;

Node* tail;

public:

DoublyLinkedList() {

head = nullptr;

tail = nullptr;

void append(int value) {

Node* newNode = new Node(value);

if (!head) {

head = newNode;

tail = newNode;

return;

newNode->prev = tail;

tail->next = newNode;

tail = newNode;

void display() {

Node* current = head;

while (current) {

std::cout << current->data << " ";

current = current->next;
}

std::cout << std::endl;

};

int main() {

DoublyLinkedList list;

list.append(10);

list.append(20);

list.append(30);

list.display();

return 0;

===================================================================================

Circular Linked List:

A circular linked list is a type of linked list where the last node's "next" pointer points back to the first
node, forming a loop.

1. Insertion at the End (Append):

o Create a new node with the given data.


o Make the last node's "next" point to the new node, and the new node's "next" point to
the first node.
o Update the "tail" pointer to the new node if needed.

2. Display:

o Traverse the list starting from the "head" node until you reach the "head" node again,
printing each node's data.
C++ code:
#include <iostream>

class Node {

public:

int data;

Node* next;

Node(int value) {

data = value;

next = nullptr;

};

class CircularLinkedList {

private:

Node* head;

Node* tail;

public:

CircularLinkedList() {

head = nullptr;

tail = nullptr;

void append(int value) {

Node* newNode = new Node(value);

if (!head) {
head = newNode;

tail = newNode;

newNode->next = head;

return;

newNode->next = head;

tail->next = newNode;

tail = newNode;

void display() {

if (!head) {

return;

Node* current = head;

do {

std::cout << current->data << " ";

current = current->next;

} while (current != head);

std::cout << std::endl;

};

int main() {

CircularLinkedList list;

list.append(10);

list.append(20);

list.append(30);

list.display();
return 0;

You might also like