double linked list in cpp

 #include <iostream>

using namespace std;

struct node

{

int data;

node *next;

node *pre;

node(int x)

{

data = x;

next = pre = NULL;

}

};

class link

{

  public:

node *head, *tail;

link()

{

head = tail = NULL;

}

void addh(int x)

{

cout << "adding as head " << x << endl;

node *curr = new node(x);

if (head == NULL)

{

head = tail = curr;

}

else

{

if (head->next == NULL)

{

head = curr;

head->next = tail;

tail->pre = head;

}

else

{

curr->next = head;

head->pre = curr;

head = curr;

}

}

}


void addt(int x)

{

cout << "adding as tail " << x << endl;

node *curr = new node(x);

if (tail == NULL)

{

head = tail = curr;

}

else

{

if (head->next == NULL)

{

tail = curr;

head->next = tail;

tail->pre = head;

}

else

{

curr->pre = tail;

tail->next = curr;

tail = curr;

}

}

}


void printh()

{

if (head == NULL)

{

cout << "list is empty " << endl;

}

else

{

cout << "\n elements from head order " << endl;

node *temp = head;

while (temp != NULL)

{

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

temp = temp->next;

}

cout << "\n"

<< endl;

}

}

void printt()

{

if (tail == NULL)

{

cout << "list is empty " << endl;

}

else

{

cout << "\n elements from tail order " << endl;

node *temp = tail;

while (temp != NULL)

{

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

temp = temp->pre;

}

cout << "\n"

<< endl;

}

}

void delt()

{

if (tail == NULL)

{

cout << "list is empty " << endl;

}

else

{

cout << "deleting tail " << tail->data << endl;

node *temp = tail->pre;

temp->next = NULL;

tail = temp;

}

}


void delh()

{

if (head == NULL)

{

cout << "list is empty " << endl;

}

else

{

cout << "deleting head " << head->data << endl;

node *temp = head->next;

temp->pre = NULL;

head = temp;

}

}

};

int main()

{

link l1;

l1.addh(56);

l1.addh(90);

l1.addt(67);

l1.addt(22);

l1.printt();

l1.printh();

l1.delt();

l1.printt();

l1.printh();

l1.delh();

l1.printh();

l1.printt();

l1.addh(3332);

l1.addt(101);

l1.addh(777);

l1.addt(666);

l1.printh();

l1.printt();

l1.delh();

l1.printh();

l1.printt();

l1.delt();

l1.printh();

l1.printt();



}

OUTPUT :












Comments