Insertion Sort List
2014-05-21 23:57
411 查看
一道值得做的题,需要机智的自己定义一个头结点。
Java code:
Java code:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode insertionSortList(ListNode head) { //逻辑短路 if(head == null || head.next == null){ return head; } ListNode headPtr = new ListNode(0); headPtr.next = head; ListNode curNode = head.next; ListNode sortedEnd = head; while(curNode != null){ ListNode preTmp = headPtr; ListNode tmp = headPtr.next; // Warning!! Not "ListNode tmp = head;" !! //remove deplicate value while(curNode.val > tmp.val && tmp != curNode){ preTmp = tmp; tmp = tmp.next; } if(curNode != tmp){ ListNode curNext = curNode.next; preTmp.next = curNode; curNode.next = tmp; sortedEnd.next = curNext; curNode = curNext; }else{ sortedEnd = curNode; curNode = curNode.next; } } return headPtr.next; } }
相关文章推荐
- leetcode:Insertion Sort List
- Insertion Sort List
- insertion-sort-list java code
- Insertion Sort List
- Insertion Sort List
- [LeetCode]Insertion Sort List
- 【Leetcode】Insertion Sort List (Sorting)
- Insertion Sort List
- 【LeetCode】Insertion Sort List
- ****(leetcode)Insertion Sort List
- Insertion Sort List
- LeetCode 147 Insertion Sort List
- Insertion Sort List
- Insertion Sort List问题及解法
- Insertion Sort List
- [leet code] Insertion Sort List
- 【leetcode】Insertion Sort List
- Insertion Sort List (Java)
- Insertion Sort List
- [Leetcode] Insertion Sort List (Java)