LeetCode 147. Insertion Sort List(插入有序链表)

来源:互联网 发布:linux命令删除文件内容 编辑:程序博客网 时间:2024/05/24 04:16

原题网址:https://leetcode.com/problems/insertion-sort-list/

Sort a linked list using insertion sort.

方法:

/** * 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 current = head.next;        head.next = null;        while (current != null) {            ListNode next = current.next;            if (current.val <= head.val) {                current.next = head;                head = current;            } else {                ListNode insert = head;                while (insert.next != null && current.val > insert.next.val) {                    insert = insert.next;                }                if (insert.next == null) {                    current.next = null;                    insert.next = current;                } else {                    current.next = insert.next;                    insert.next = current;                }            }            current = next;        }        return head;    }}

优化:

/** * 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) {    /*    下面这个是网上找来的    */        ListNode dummy = new ListNode(0);        // 这个dummy的作用是,把head开头的链表一个个的插入到dummy开头的链表里        // 所以这里不需要dummy.next = head;        while (head != null) {            ListNode node = dummy;            while (node.next != null && node.next.val < head.val) {                node = node.next;            }            ListNode temp = head.next;            head.next = node.next;            node.next = head;            head = temp;        }        return dummy.next;    }}


0 0
原创粉丝点击