链表系列之排序循环列表,避免死循环和边缘情况完整处理!

214 阅读2分钟

题目

image.png

解析

  • 题目其实很好理解吧,就是往一个递增的链表里面多增加一个值去且要保证它保持递增
  • 情况1:传进来的链表值是空,就让插入值生成一个节点指向自身
  • 情况2:传进来的链表只有一个节点,就让它的next指向新节点,新节点指向它
  • 情况3:传进来的链表大于两个节点,如果要插入的值比这个链表的最大最小值大或大我们就将它插入在链表最大和最小值之间,如果不是就插入到大于这个值和小于这个值的相邻节点中间

主要代码

function addVal(head, val) {
    const node = new listNode(val, null)

    // 处理传入空节点情况
    if (head === null) {
        node.next = node
        return head
    }

    // 处理传入单个节点情况
    if (head.next === null) {
        head.next = node
        node.next = head
        return head
    }

    let cur = head
    let next = head.next
    let biggest = head.val

    // 前半部分判断用于找到两个满足条件的相邻节点,后半部分的判断用于避免死循环
    while(!(cur.val <= val && next.val >= val) && next!== head) {
        cur = cur.next
        next = next.next

        if (cur.val > biggest) {
            biggest = cur.val
        }
    }

    // 如果要插入的值存在两个相邻节点小于和大于它就插入在这两个节点中间
    if (cur.val <= val && next.val >= val) {
        const temp = cur.next
        cur.next = node
        node.next = temp
    } else { // 如果没有就插入在最大值和最小值中间
        const temp = biggest.next
        biggest.next = node
        node.next = temp
    }

    return head
}

结合测试用例

class listNode {
    constructor(val, next) {
        this.val = val;
        this.next = next;
    }
}

const head = new listNode(1, null)
head.next = new listNode(2, null)
head.next.next = new listNode(4, null)
head.next.next.next = new listNode(6, head)

function addVal(head, val) {
    const node = new listNode(val, null)

    // 处理传入空节点情况
    if (head === null) {
        node.next = node
        return head
    }

    // 处理传入单个节点情况
    if (head.next === null) {
        head.next = node
        node.next = head
        return head
    }

    let cur = head
    let next = head.next
    let biggest = head.val

    // 前半部分判断用于找到两个满足条件的相邻节点,后半部分的判断用于避免死循环
    while(!(cur.val <= val && next.val >= val) && next!== head) {
        cur = cur.next
        next = next.next

        if (cur.val > biggest) {
            biggest = cur.val
        }
    }

    // 如果要插入的值存在两个相邻节点小于和大于它就插入在这两个节点中间
    if (cur.val <= val && next.val >= val) {
        const temp = cur.next
        cur.next = node
        node.next = temp
    } else { // 如果没有就插入在最大值和最小值中间
        const temp = biggest.next
        biggest.next = node
        node.next = temp
    }

    return head
}

console.log(addVal(head, 3));