Insertion Sort List

来源:互联网 发布:python给字典添加新值 编辑:程序博客网 时间:2024/05/22 15:32

public class Solution {    public ListNode insertionSortList(ListNode head) {      if (head == null) {        return null;        }        ListNode newHeadNode = new ListNode(head.val);        head = head.next;        while (head != null) {        ListNode insertNode = new ListNode(head.val);        ListNode prev = null;        ListNode cur = newHeadNode;        while (cur != null) {        if (insertNode.val < cur.val) {if (prev == null) {insertNode.next = cur;newHeadNode = insertNode;break;}else {prev.next = insertNode;insertNode.next = cur;break;}}        else {        prev = cur;        cur = cur.next;        }        }        if (cur == null) {prev.next = insertNode;insertNode.next = null;}        head = head.next;        }        return newHeadNode;    }}

Sort a linked list using insertion sort.

Nothing much to explain. Just be careful when you insert this node at the beginning or at the end.


0 0