Leetcode Insertion Sort List 插入排序链表
2015-05-06 15:34
453 查看
题目:
Sort a linked list using insertion sort.分析:
1. 创建一个新的链表。2. 对原链表中的每个元素,从新链表表头开始找该元素插入的位置,找到后插入元素。
Java代码实现:
/*** Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode dummy = new ListNode(0);
dummy.next = new ListNode(head.val);
head = head.next;
ListNode node = dummy.next;
ListNode pre = dummy;
while(head!=null)
{
while(node!=null && head.val>=node.val)
{
pre = node;
node = node.next;
}
pre.next = new ListNode(head.val);
pre.next.next = node;
node = dummy.next;
pre = dummy;
head = head.next;
}
return dummy.next;
}
}
相关文章推荐
- LeetCode 147 Insertion Sort List(链表插入排序)
- [C++]LeetCode: 126 Insertion Sort List (插入排序链表)
- leetcode Insertion Sort List(链表插入排序)
- LeetCode Insertion Sort List 链表的插入排序
- leetcode——Insertion Sort List 对链表进行插入排序(AC)
- [LeetCode147]Insertion Sort List(链表插入排序)
- LeetCode Insertion Sort List(单链表插入排序)
- LeetCode:Insertion Sort List//链表插入排序
- 【LeetCode-面试算法经典-Java实现】【147-Insertion Sort List(链表插入排序)】
- LeetCode 147 Insertion Sort List(链表)
- leetcode---insertion-sort-list---链表
- LeetCode Insertion Sort List 链表插入排序
- 链表的插入排序 Insertion Sort List
- 173. 链表插入排序 (insertion-sort-list)(c++)----lintcode面试题之链表
- LeetCode | Insertion Sort List(插入法排序链表)
- Insertion Sort List(单链表插入排序)
- leetcode 链表 Insertion Sort List
- 【leetcode】【单链表】【147】Insertion Sort List
- leetcode_147题——Insertion Sort List(线性表,插入排序)
- leetcode_效率题解_[python/C++]_147. Insertion Sort List(链表插入排序)