[LeetCode]Insertion Sort List
2014-03-04 22:28
274 查看
题目描述
Sort a linked list using insertion sort.使用插入排序法对一个链表进行排序
解题思路
刚开始看觉得so easy,直到真正写代码了,才发现好繁琐。我们对当前的node插入到已经排好序的链表中。我们用head和tail来表示已排序好子链表的头和尾。
需要考虑node插入到head之前,插入到tail之后,和插入到head和tail之间三种情况。
代码
public ListNode insertionSortList(ListNode head) { if(head==null){ return null; } ListNode node = head.next; ListNode tempHead = head,tempNode = head,tempTail = head; ListNode lastNode = null; int len = 1; while(node!=null){ tempNode = tempHead; int i = 0; for(i = 0;i < len;i++){ if(node.val < tempNode.val){ if(i==0){ //插入到head之前 tempTail.next = node.next; node.next = tempNode; tempHead = node;//重新确立头节点 break; }else { //插入到head和tail之间 lastNode.next = node; tempTail.next = node.next; node.next = tempNode; break; } } lastNode = tempNode;//记住遍历时的上一节点 tempNode = tempNode.next; } if(i==len){ //位置不变,插入到tail之后,tail等于当前的node tempTail = node; } len++; node = tempTail.next;; } return tempHead; }
相关文章推荐
- 【LeetCode】Insertion Sort List
- 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 problem 5: 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
- Insertion Sort List Leetcode Python
- leetcode上的Sort a linked list using insertion sort
- 和大神们学习每天一题(leetcode)-Insertion Sort List
- Leetcode -- Insertion Sort List