Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #with changing data fileds
- # Definition for singly-linked list.
- # class ListNode:
- # def __init__(self, val=0, next=None):
- # self.val = val
- # self.next = next
- class Solution:
- def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
- def exchange(a,b):
- a.val,b.val=b.val,a.val
- def qsort(start,end):
- if start!=end:
- piv=mid=start
- j=start.next
- while j:
- if j.val<piv.val:
- mid=mid.next
- exchange(j,mid)
- j=j.next
- exchange(mid,piv)
- qsort(start,mid)
- qsort(mid.next,end)
- qsort(head,None)
- return head
- #without changing data pointers ,data no swap code
- #User function Template for python3
- def quickSort(head):
- def qsort(h):
- if not h:return h#base case
- dl,dm,dr=Node(-1),h,Node(-1)# temporary headers dm:equal dl:less than piv dr:gt than piv
- l,m,r=dl,dm,dr#l,m,r traversing ptrs
- piv,cur=h,h.next#pivot is head
- while cur:#iterate cur
- if cur.data==h.data:
- m.next=cur
- m=m.next
- elif cur.data<h.data:
- l.next=cur
- l=l.next
- else:
- r.next=cur
- r=r.next
- cur=cur.next
- l.next=r.next=m.next=None# ending the dl,dm,dr lists
- dl.next=qsort(dl.next)
- dr.next=qsort(dr.next)
- res=dl#combining list
- while res.next:
- res=res.next
- res.next=dm# since dm list have atleast one element for sure
- m.next=dr.next
- return dl.next
- return qsort(head)
Add Comment
Please, Sign In to add comment