【LeetCode】Insertion Sort List
2014-05-11 12:58
330 查看
Sort a linked list using insertion sort.
//用到O(N)的额外空间 public class Solution { public ListNode insertionSortList(ListNode head) { if(head==null||head.next==null) return head; ListNode root = new ListNode(head.val); ListNode cur = head.next; while(cur!=null){ ListNode tempNode = root; ListNode pre = root; while(tempNode!=null){ if(cur.val>tempNode.val){ pre=tempNode; tempNode=tempNode.next; }else{ break; } } if(tempNode==root){ ListNode newNode = new ListNode(cur.val); newNode.next=root; root=newNode; cur=cur.next; }else if(tempNode==null){ ListNode newNode = new ListNode(cur.val); pre.next=newNode; cur=cur.next; }else{ ListNode newNode = new ListNode(cur.val); pre.next=newNode; newNode.next=tempNode; cur=cur.next; } } return root; } }
public class NSolution { public ListNode insertionSortList(ListNode head) { if(head==null||head.next==null) return head; ListNode cur = head.next; head.next=null; while(cur!=null){ ListNode tempNode = head; ListNode pre = head; while(tempNode!=null){ if(cur.val>tempNode.val){ pre=tempNode; tempNode=tempNode.next; }else{ break; } } if(tempNode==head){ ListNode newNode = new ListNode(cur.val); newNode.next=head; head=newNode; cur=cur.next; }else if(tempNode==null){ ListNode newNode = new ListNode(cur.val); pre.next=newNode; cur=cur.next; }else{ ListNode newNode = new ListNode(cur.val); pre.next=newNode; newNode.next=tempNode; cur=cur.next; } } return head; } }
相关文章推荐
- leetcode---Insertion Sort List
- Insertion Sort List Leetcode Python
- leetcode上的Sort a linked list using insertion sort
- [LeetCode]Insertion Sort List
- Leetcode | Insertion Sort List | 初出茅庐
- leetcode-Insertion Sort List
- 【Leetcode】Insertion Sort List (Sorting)
- 【LeetCode】Insertion Sort List 解题报告
- leetcode--Insertion Sort List
- Leetcode:Insertion Sort List
- 【Leetcode】Insertion Sort List
- LeetCode---Insertion Sort List
- LeetCode Insertion Sort List
- 【leetcode】【单链表】【147】Insertion Sort List
- leetcode insertion-sort-list
- [LeetCode] Insertion Sort List
- [LeetCode] Insertion Sort List
- leetcode 名单 Insertion Sort List
- leetcode Insertion Sort List
- 和大神们学习每天一题(leetcode)-Insertion Sort List