Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct Node
- {
- struct Node* previous;
- struct Node* next;
- int data;
- } *first = NULL, *last = NULL;
- void add(int x)
- {
- if(first == NULL)
- {
- first = new Node;
- first->data = x;
- first->previous = NULL;
- first->next = NULL;
- last = first;
- }
- else
- {
- Node *t = new Node;
- t->data = x;
- t->previous = last;
- t->next = NULL;
- last->next = t;
- last = t;
- }
- }
- void display(struct Node *p)
- {
- while(p)
- {
- cout << p->data << " ";
- p = p->next;
- }
- }
- void displayReverse(struct Node*p)
- {
- while(p)
- {
- cout << p->data << " ";
- p = p->previous;
- }
- }
- void insertAfter(int key, int val)
- {
- Node *p = first;
- if(first->data == key)
- {
- Node *t = new Node;
- t->data = val;
- t->previous = first;
- t->next = first->next;
- first->next->previous = t;
- first->next = t;
- }
- else
- {
- while(p->data!=key)
- {
- p = p->next;
- }
- Node *t = new Node;
- t->data = val;
- t->next = p->next;
- t->previous = p;
- p->next = t;
- }
- }
- void deleteAfter(int key)
- {
- Node *p = first;
- if(key == first->data)
- {
- Node *t = first;
- first = first->next;
- first->previous = NULL;
- delete t;
- }
- else
- {
- while(p->data !=key )
- {
- p = p->next;
- }
- Node *t = new Node;
- t = p->next;
- if(t->next == NULL)
- {
- p ->next = NULL;
- }
- else
- {
- p->next =p->next->next;
- p->next->previous = p;
- }
- delete t;
- }
- }
- void insertBefore(int key, int val)
- {
- Node *p = first;
- if(p->data == key)
- {
- Node *t = new Node;
- t->next = first->next;
- t->previous = NULL;
- t->data = val;
- first = t;
- }
- else
- {
- while(p->data!=key)
- {
- p = p->next;
- }
- Node *t = new Node;
- t->data = val;
- t->next = p;
- t->previous = p->previous;
- p->previous->next = t;
- p->previous = t;
- }
- }
- int main()
- {
- add(11);
- add(2);
- add(3);
- add(5);
- add(6);
- add(4);
- display(first);
- cout << endl;
- //insertAfter(2,10);
- //deleteAfter(6);
- insertBefore(3,9);
- display(first);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement