Hi, I am Aman Kumar pursuing BCA II. I have decided to write what i learn daily.

I request you to please go through this program and feel free to write me if you have any advice/suggestions for me at 2022amankumar@gmail.com 

Implementing Doubly linked list.

#include<iostream>

using namespace std;

struct Node{

int data;

Node *next;

Node *prev;

};

class DoublyLinkedList{

public:

Node *head;

Node* GetNewNode(int x)

{

Node *newNode=new Node;

newNode->data=x;

newNode->prev=NULL;

newNode->next=NULL;

return newNode;

}

void InsertAtHead(int x)

{

Node* newNode=GetNewNode(x);

if(head==NULL)

{

head=newNode;

return;

}

head->prev=newNode;

newNode->next=head;

head=newNode;

}

void Print()

{

Node* temp=head;

cout<<"Forward: ";

while(temp!=NULL)

{

cout<<temp->data<<" ";

temp=temp->next;

}

printf("\n");

}

void ReversePrint()

{

Node* temp=head;

if(head==NULL)

return;

while(temp->next !=NULL)

{

temp=temp->next;

}

cout<<"Reverse: ";

while(temp!=NULL)

{

cout<<temp->data<<" ";

temp=temp->prev;

}

printf("\n");

}

void InsertAtTail(int x)

{

Node* newNode=GetNewNode(x);

if(head==NULL)

{

head=newNode;

return;

}

Node* tail=head;

while(tail->next!=NULL)

tail=tail->next;

tail->next=newNode;

newNode->prev=tail;

}

};

int main()

{

DoublyLinkedList test;

test.head=NULL;

test.InsertAtHead(2); test.Print(); test.ReversePrint();

test.InsertAtHead(4); test.Print(); test.ReversePrint();

test.InsertAtHead(6); test.Print(); test.ReversePrint();

test.InsertAtTail(56);test.Print(); test.ReversePrint();

}

Comments