鏈表相關面試題

使用插入排序對鏈表進行排序(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;

    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章