Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- https://www.interviewbit.com/problems/detect-and-remove-loop-from-a-linked-list/
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * ListNode *next;
- * ListNode(int x) : val(x), next(NULL) {}
- * };
- */
- typedef ListNode node;
- ListNode* Solution::solve(ListNode* a) {
- node*b,*c,*x;
- b=c=x=a;
- /*while(x->next!=NULL and x!=NULL)
- {
- x=x->next->next;
- }*/
- cout<<"1111111111"<<endl;
- while(b!=c)
- {
- b=b->next;c=c->next->next;
- if(b==NULL || c==NULL)return a;
- }
- c=c->next;
- cout<<"2222222222222"<<endl;
- int count=1;
- while(c!=b)
- {
- c=c->next;
- count++;
- cout<<count;
- }
- cout<<"333333333333333"<<endl;
- node*d,*e;
- d=e=a;
- for(int i=0;i<count;i++)
- {
- e=e->next;
- }
- cout<<"44444444444"<<endl;
- while(d!=e)
- {
- d=d->next;e=e->next;
- }
- cout<<"55555555555555"<<endl;
- cout<<d->val<<endl;
- for(int i=1;i<count;i++)
- {
- e=e->next;
- }
- cout<<"666666666666666"<<endl;
- e->next=NULL;
- return a;
- }
Add Comment
Please, Sign In to add comment