Advertisement
spider68

linked list implementation

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