Skip to content

Latest commit

 

History

History
69 lines (57 loc) · 1.95 KB

147.md

File metadata and controls

69 lines (57 loc) · 1.95 KB

✏️Leetcode基础刷题之(147. Insertion Sort List)

2019-09-11 吴亲库里 库里的深夜食堂


✏️描述

使用插入排序对链表进行从小到达排序。来张动态图


✏️题目实例

✏️题目分析

其实就是把当前链表中的结点一个个取出,然后插入到新的链表当中,插入的时候把当前结点的值和新链表头结点进行比较,如果比头结点还小那就直接成为新的头,否则通过next指针直到找到对应的位置即可。

/**
 * Definition for a singly-linked list.
 * class ListNode {
 *     public $val = 0;
 *     public $next = null;
 *     function __construct($val) { $this->val = $val; }
 * }
 */
class Solution {

    /**
     * @param ListNode $head
     * @return ListNode
     */
    function insertionSortList($head) {
        if(!$head || !$head->next) return $head;
        $p=$head->next;
        $head->next=null;
        while($p !==null){
            $pNext=$p->next;
            $q=$head;
            if($p->val<$q->val){
                $p->next=$q;
                $head=$p;
            }else{
                while($q !=null && $q->next !=null && $q->next->val<$p->val){
                    $q=$q->next;
                }
                $p->next=$q->next;
                $q->next=$p;
            }
            $p=$pNext;
        }
        return $head;
    }
}

联系