Advertisement
spider68

doubly linked list implementation

Jul 24th, 2021
1,137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.90 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3. class dlist{
  4.     public:
  5.         int data;
  6.         dlist*right;
  7.         dlist*left;
  8.         dlist(int n){
  9.             this->data=n;
  10.             left=NULL;
  11.             right=NULL;
  12.         }
  13. };
  14. void print(dlist*tmp){
  15.     while(tmp){
  16.         cout<<tmp->data<<" ";
  17.         tmp=tmp->right;
  18.     }
  19.     cout<<endl;
  20. }
  21.  
  22. void push(dlist* &node,int n){
  23.     dlist*tmp=new dlist(n);
  24.     tmp->right=node;
  25.     node->left=tmp;
  26.     node=tmp;
  27. }
  28.  
  29. void deletenode(dlist* &node,int x){
  30.     if(!node)return;
  31.     if(node->data==x){
  32.         node=node->right;
  33.         node->left=NULL;
  34.         return;
  35.     }
  36.     dlist*tmp=node;
  37.     while(tmp->right!=NULL && tmp->right->data != x){
  38.         tmp=tmp->right;
  39.     }
  40.     if(tmp->right){
  41.         tmp->right=tmp->right->right;
  42.         if(tmp->right)tmp->right->left=tmp;
  43.     }
  44. }
  45. void reverse(dlist* &node){
  46.     if(!node || !node->right)return;
  47.     dlist*curr=node,*prev=NULL;
  48.     while(curr){
  49.         dlist*next=curr->right;
  50.         curr->right=prev;
  51.         curr->left=next;
  52.         prev=curr;
  53.         curr=curr->left;
  54.     }
  55.     node=prev;
  56. }
  57. void middle(dlist* node){
  58.     if(!node)cout<<-1<<endl;
  59.     else if(!node->right)cout<<node->data<<endl;
  60.     else{
  61.         dlist*slow=node,*fast=node->right;
  62.         while(fast && fast->right){
  63.             slow=slow->right;
  64.             fast=fast->right->right;
  65.         }
  66.         cout<<slow->data<<" ";
  67.         if(fast)cout<<slow->right->data<<" ";
  68.         cout<<endl;
  69.     }
  70. }
  71. int main(){
  72.     dlist*head=new dlist(0);
  73.     push(head,1);
  74.     push(head,2);
  75.     push(head,4);
  76.     push(head,5);
  77.     push(head,6);
  78.     print(head);
  79.     deletenode(head,3);
  80.     print(head);
  81.     deletenode(head,0);
  82.     print(head);
  83.     deletenode(head,6);
  84.     print(head);
  85.     reverse(head);
  86.     print(head);
  87.     middle(head);
  88.     push(head,7);
  89.     print(head);
  90.     middle(head);
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement