
Insertion Sort List
Question
Sort a linked list using insertion sort.
Analysis
An easy and clear way to sort ( O(1) space )
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
* Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class { public ListNode insertionSortList(ListNode head) { if(head==null||head.next==null) return head; ListNode next=new ListNode(1); ListNode cur=head; ListNode res=new ListNode(1); ListNode pre=res; while(cur!=null){ next=cur.next; while(pre!=null&&pre.next!=null&&pre.next.val<cur.val){ pre=pre.next; } cur.next=pre.next; pre.next=cur; cur=next; pre=res; } return res.next; } }
|
Sort List
Question
Sort a linked list in O(n log n) time using constant space complexity.
Analysis
Java Merge Sort Solution
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
* Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class { public ListNode sortList(ListNode head) { if(head==null||head.next==null) return head; ListNode slow=head; ListNode fast=head; ListNode prev=null; while(fast!=null&&fast.next!=null){ prev=slow; slow=slow.next; fast=fast.next.next; } prev.next=null; ListNode l1=sortList(head); ListNode l2=sortList(slow); return Merge(l1,l2); } public ListNode Merge(ListNode l1, ListNode l2){ ListNode p=new ListNode(1); ListNode res=p; while(l1!=null&&l2!=null){ if(l1.val>l2.val){ res.next=l2; l2=l2.next; } else{ res.next=l1; l1=l1.next; } res=res.next; } if(l1!=null) res.next=l1; if(l2!=null) res.next=l2; return p.next; } }
|
近期评论