【LeetCode】Insertion Sort List
2014-07-09 14:29
295 查看
题目
Sort a linked list using insertion sort.
解答
链表无法像数组那样从后往前依次比较插入,只能从前往后;在链表首部添加一个哨兵可以稍微简化下代码,代码如下:
/**
* 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 list=new ListNode(-1);
ListNode pre=list;
ListNode cur=head;
while(cur!=null){
ListNode temp=cur.next; //先用临时的temp将cur的下一节点存起来
pre=list; //将已排的有序链表list赋给pre
while(pre.next!=null&&pre.next.val<cur.val){ //比要比较的值小的,指针指向下一节点
pre=pre.next;
}
cur.next=pre.next; //将要比较的节点和有序的后半部分连接起来
pre.next=cur; //将前半部分和后半部分连接起来
cur=temp; //相当于指针移到下一节点
}
return list.next;
}
}
---EOF---
Sort a linked list using insertion sort.
解答
链表无法像数组那样从后往前依次比较插入,只能从前往后;在链表首部添加一个哨兵可以稍微简化下代码,代码如下:
/**
* 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 list=new ListNode(-1);
ListNode pre=list;
ListNode cur=head;
while(cur!=null){
ListNode temp=cur.next; //先用临时的temp将cur的下一节点存起来
pre=list; //将已排的有序链表list赋给pre
while(pre.next!=null&&pre.next.val<cur.val){ //比要比较的值小的,指针指向下一节点
pre=pre.next;
}
cur.next=pre.next; //将要比较的节点和有序的后半部分连接起来
pre.next=cur; //将前半部分和后半部分连接起来
cur=temp; //相当于指针移到下一节点
}
return list.next;
}
}
---EOF---
相关文章推荐
- 【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
- leetcode Insertion Sort List
- Insertion Sort List--leetcode
- LeetCode problem 5: Insertion Sort List
- [leetcode 147] Insertion Sort List
- LeetCode Insertion Sort List
- LeetCode_Insertion Sort List
- [leetcode][list][sort] Insertion Sort List
- 《leetCode》:Insertion Sort List
- LeetCode :: Insertion Sort List [详细分析]
- LeetCode:Insertion Sort List
- Insertion Sort List ---LeetCode
- [leetcode]Insertion Sort List
- leetcode: Insertion Sort List
- [leetcode]Insertion Sort List