链表相关面试题

来源:互联网 发布:abp源码 编辑:程序博客网 时间:2024/05/22 03:20

使用插入排序对链表进行排序(Sort a linked list using insertion sort.):

public  ListNode insertionSortList(ListNode head) {        if (head == null) {            return head;        }        ListNode toInsert = head;        ListNode newHead = null;        while (toInsert != null) {            ListNode cur = newHead;            ListNode next = toInsert.next;            // 判断头部            if (cur == null||toInsert.val <= newHead.val) {                toInsert.next = cur;                newHead = toInsert;            } else {                while (cur.next != null) {                    if (cur.val <= toInsert.val && toInsert.val <= cur.next.val) {                        toInsert.next = cur.next;                        cur.next = toInsert;                        break;                    }                    cur =cur.next;                }                //如果待插入的数是最大的,就把它放在后面                if (cur.next == null) {                    cur.next = toInsert;                    toInsert.next = null;                }            }            toInsert = next;        }        return newHead;    }
原创粉丝点击