Insertion Sort List
2014-09-27 14:58
148 查看
Problem:
Sort a linked list using insertion sort.
Solution:
/**
* 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) {
ListNode h = new ListNode(-1);
h.next = head;
ListNode p = head;
if(p==null||p.next==null)
return p;
while(p.next!=null)
{
while(p.next!=null&&p.val<=p.next.val)
{
p = p.next;
}
if(p.next==null)
break;
ListNode q = h;
while(q.next!=null&&q.next.val<=p.next.val)
{
q = q.next;
}
ListNode temp = q.next;
q.next = p.next;
p.next = p.next.next;
q.next.next = temp;
}
return h.next;
}
}
Sort a linked list using insertion sort.
Solution:
/**
* 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) {
ListNode h = new ListNode(-1);
h.next = head;
ListNode p = head;
if(p==null||p.next==null)
return p;
while(p.next!=null)
{
while(p.next!=null&&p.val<=p.next.val)
{
p = p.next;
}
if(p.next==null)
break;
ListNode q = h;
while(q.next!=null&&q.next.val<=p.next.val)
{
q = q.next;
}
ListNode temp = q.next;
q.next = p.next;
p.next = p.next.next;
q.next.next = temp;
}
return h.next;
}
}
相关文章推荐
- [LeetCode] Insertion Sort List
- Insertion Sort List ---LeetCode
- [LeetCode] Insertion Sort List 单向链表插入排序
- [LeetCode OJ] Insertion Sort List 解题报告
- Leetcode:Insertion Sort List
- 插入排序(Insertion Sort List)
- leetcode Insertion Sort List(链表插入排序)
- leetcode Insertion Sort List
- Insertion Sort List
- Leetcode---Insertion Sort List
- leetcode-147 Insertion Sort List
- [Linked List]Insertion Sort List
- leetcode--Insertion Sort List
- [leetcode]Insertion Sort List
- Insertion Sort List
- leetcode -- Insertion Sort List
- LeetCode :Insertion Sort List
- 【Leetcode】Insertion Sort List
- leetcode Insertion Sort List
- 59_leetcode_Insertion Sort List