Iam_Sandeep

Remove loop in linked list

Apr 2nd, 2022
1,319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.18 KB | None | 0 0
  1.  
  2.  
  3. class Solution:
  4.     def removeLoop(self, head):
  5.         def remove(x):
  6.             if x==head:
  7.                 t=head
  8.                 while t.next!=head:t=t.next
  9.                 t.next=None
  10.             else:
  11.                 t=head
  12.                 while t.next!=x.next:
  13.                     t,x=t.next,x.next
  14.                 x.next=None
  15.                
  16.         s=f=head
  17.         while f.next and f.next.next:
  18.             s,f=s.next,f.next.next
  19.             if s==f:
  20.                 remove(s)
  21.                 return
  22.         return
  23.            
  24.  
  25.  
  26. #{
  27. #  Driver Code Starts
  28. # driver code:
  29.  
  30. class Node:
  31.     def __init__(self,val):
  32.         self.next=None
  33.         self.data=val
  34.  
  35. class linkedList:
  36.     def __init__(self):
  37.         self.head=None
  38.         self.tail=None
  39.    
  40.     def add(self,num):
  41.         if self.head is None:
  42.             self.head=Node(num)
  43.             self.tail=self.head
  44.         else:
  45.             self.tail.next=Node(num)
  46.             self.tail=self.tail.next
  47.    
  48.     def isLoop(self):
  49.         if self.head is None:
  50.             return False
  51.        
  52.         fast=self.head.next
  53.         slow=self.head
  54.        
  55.         while slow != fast:
  56.             if fast is None or fast.next is None:
  57.                 return False
  58.             fast=fast.next.next
  59.             slow=slow.next
  60.        
  61.         return True
  62.    
  63.     def loopHere(self,position):
  64.         if position==0:
  65.             return
  66.        
  67.         walk=self.head
  68.         for _ in range(1,position):
  69.             walk=walk.next
  70.         self.tail.next=walk
  71.    
  72.     def length(self):
  73.         walk=self.head
  74.         ret=0
  75.         while walk:
  76.             ret+=1
  77.             walk=walk.next
  78.         return ret
  79.  
  80. if __name__=="__main__":
  81.     t=int(input())
  82.     for _ in range(t):
  83.         n=int(input())
  84.         arr=tuple(int(x) for x in input().split())
  85.         pos=int(input())
  86.        
  87.         ll = linkedList()
  88.         for i in arr:
  89.             ll.add(i)
  90.         ll.loopHere(pos)
  91.        
  92.         Solution().removeLoop(ll.head)
  93.        
  94.         if ll.isLoop() or ll.length()!=n:
  95.             print(0)
  96.             continue
  97.         else:
  98.             print(1)
  99.  
  100. # } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment