147. Insertion Sort List

来源:互联网 发布:湖北广电网络宽带资费 编辑:程序博客网 时间:2024/04/24 17:52

Sort a linked list using insertion sort.


不需要额外空间,只需要一个辅助头节点,遍历链表,保存当前节点的后继节点,找到当前节点应该插入到新链表的什么位置,在新链表里做插入操作,再取原来保存的后继节点继续遍历下去。


public class Solution {    public static ListNode insertionSortList(ListNode head){if (head == null || head.next == null)return head;ListNode dummy = new ListNode(Integer.MIN_VALUE);ListNode node = head;while (node != null){ListNode find = dummy;while (find.next != null && find.next.val < node.val)find = find.next;ListNode nodenext=node.next;node.next=find.next;find.next=node;node=nodenext;}return dummy.next;}}


0 0
原创粉丝点击