美文网首页
对链表进行插入排序

对链表进行插入排序

作者: 叫我宫城大人 | 来源:发表于2019-05-05 21:25 被阅读0次

题目

对一个无序单向链表进行插入排序。

思想

运用哨兵思想,简化链表边界问题。

示例

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode insertionSortList(ListNode head) {
        // 构造哨兵节点
        ListNode sentinel = new ListNode(0);
        while (head != null) {
            ListNode p = sentinel, next = head.next;
            while (p.next != null && p.next.val <= head.val) {
                p = p.next;
            }
            // 链表插入
            head.next = p.next;
            p.next = head;
            // 指针重置
            head = next;
        }
        return sentinel.next;
    }
}

相关文章

网友评论

      本文标题:对链表进行插入排序

      本文链接:https://www.haomeiwen.com/subject/waskoqtx.html