Leetcode Insertion Sort List
2016-07-19 05:02
471 查看
Sort a linked list using insertion sort.
Difficulty: Medium
/**
* 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) return null;
ListNode tail = head;
ListNode curr;
while(tail.next != null){
if(tail.next.val <= head.val){
ListNode temp = tail.next;
tail.next = temp.next;
temp.next = head;
head = temp;
}
else if(tail.next.val >= tail.val){
tail = tail.next;
}
else{
ListNode pre = null;
curr = head;
while(curr.val < tail.next.val){
pre = curr;
curr = curr.next;
}
ListNode temp = tail.next;
tail.next = temp.next;
pre.next = temp;
temp.next = curr;
}
}
return head;
}
}
Difficulty: Medium
/**
* 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) return null;
ListNode tail = head;
ListNode curr;
while(tail.next != null){
if(tail.next.val <= head.val){
ListNode temp = tail.next;
tail.next = temp.next;
temp.next = head;
head = temp;
}
else if(tail.next.val >= tail.val){
tail = tail.next;
}
else{
ListNode pre = null;
curr = head;
while(curr.val < tail.next.val){
pre = curr;
curr = curr.next;
}
ListNode temp = tail.next;
tail.next = temp.next;
pre.next = temp;
temp.next = curr;
}
}
return head;
}
}
相关文章推荐
- Leetcode Unique Binary Search Trees
- Leetcode Linked List Cycle II
- Leetcode Remove Nth Node From End of List
- Leetcode Integer to Roman
- Leetcode Valid Anagram
- Leetcode Single Number II
- 大公司还是小公司(非常全面和有道理,居然还是原创)
- Leetcode Pascal's Triangle
- Leetcode Balanced Binary Tree
- Leetcode Divide Two Integers
- Leetcode Sqrt(x)
- Leetcode Number of Digit One
- Leetcode Largest Number
- Leetcode Word Break II
- [leetcode] 118. Pascal's Triangle
- php判断是否为今天
- Codeforces Round #327 (Div. 2)
- 决策树算法(四)——选取最佳特征划分数据集
- 一键安装LAMP或LNMP
- [leetcode] 110. Balanced Binary Tree