math2do

Untitled

Oct 10th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. https://www.interviewbit.com/problems/detect-and-remove-loop-from-a-linked-list/
  2.  
  3.  
  4.  
  5. /**
  6.  * Definition for singly-linked list.
  7.  * struct ListNode {
  8.  *     int val;
  9.  *     ListNode *next;
  10.  *     ListNode(int x) : val(x), next(NULL) {}
  11.  * };
  12.  */
  13.  typedef ListNode node;
  14. ListNode* Solution::solve(ListNode* a) {
  15.     node*b,*c,*x;
  16.     b=c=x=a;
  17.     /*while(x->next!=NULL and x!=NULL)
  18.     {
  19.         x=x->next->next;
  20.     }*/
  21.     cout<<"1111111111"<<endl;
  22.     while(b!=c)
  23.     {
  24.         b=b->next;c=c->next->next;
  25.         if(b==NULL || c==NULL)return a;
  26.     }
  27.    
  28.     c=c->next;
  29.     cout<<"2222222222222"<<endl;
  30.     int count=1;
  31.     while(c!=b)
  32.     {
  33.         c=c->next;
  34.         count++;
  35.         cout<<count;
  36.     }
  37.     cout<<"333333333333333"<<endl;
  38.     node*d,*e;
  39.     d=e=a;
  40.     for(int i=0;i<count;i++)
  41.     {
  42.         e=e->next;
  43.     }
  44.     cout<<"44444444444"<<endl;
  45.     while(d!=e)
  46.     {
  47.         d=d->next;e=e->next;
  48.     }
  49.     cout<<"55555555555555"<<endl;
  50.     cout<<d->val<<endl;
  51.    
  52.     for(int i=1;i<count;i++)
  53.     {
  54.         e=e->next;
  55.     }
  56.     cout<<"666666666666666"<<endl;
  57.     e->next=NULL;
  58.     return a;
  59. }
Add Comment
Please, Sign In to add comment