147 insertion sort list

| 分类 leetcode  | 标签 sort 

Sort a linked list using insertion sort.

1
2
3
4
5
6
7
8
9
10
11
12
/*
 * 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) {
} }

1

插入排序的链表实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public ListNode insertionSortList(ListNode head){
        if(head == null || head.next == null) return head;
        ListNode dummyHead = new ListNode(0);
        while(head != null){
            ListNode pre = dummyHead;
            while(pre.next != null && pre.next.val < head.val){
                pre = pre.next;
            }
            ListNode tmp = head.next;
            head.next = pre.next;
            pre.next = head;
            head = tmp;
        }
        return dummyHead.next;
    }

2 most votes

一样。


上一篇     下一篇