In: Computer Science
In a double linked chain, each node can point to the previous node as well as the next node. In a double linked chain, each node can point to the previous node as well as the next node.
Here I am implementing doubly linked list in cpp.
If any issue plzz comment below
#include <iostream>
using namespace std;
//Here structure of a doubly linked list.
struct Node {
int data; //point to the data in the linked list
struct Node *prev; //point to left node
struct Node *next; //point to right node
};
//Header node initialization
struct Node* head = NULL;
//function to add new Data
void insert(int newdata) {
//create a new node for doubly linked list
struct Node* newnode = (struct Node*) malloc(sizeof(struct Node));
//insert data
newnode->data = newdata;
//first point the left node to null
newnode->prev = NULL;
//put the address of current head node to right of new node
newnode->next = head;
//if head is not null
if(head != NULL)
//put the address of new node to left of head node
head->prev = newnode ;
//make the current node as head node
head = newnode;
}
//To display the doubly linked list
void display() {
struct Node* ptr;
ptr = head;
//iterate until we get null address
while(ptr != NULL) {
cout<< ptr->data <<" ";
ptr = ptr->next;
}
}
//main function
int main() {
insert(9);
insert(10);
insert(7);
insert(4);
insert(9);
insert(54);
cout<<"The doubly linked list is: ";
display();
return 0;
}
Output: