源代码

/* 顺序线性表(数组)实现*/

class SequentialList {
    constructor(array = []) {
        this.data = [...array];
    }

// 删除所有负整数元素(保持相对顺序)
    removeNegatives() {
// 使用双指针法
        let writeIndex = 0;

        for (let readIndex = 0; readIndex < this.data.length; readIndex++) {
            if (this.data[readIndex] >= 0) {
                this.data[writeIndex] = this.data[readIndex];
                writeIndex++;
            }
        }

// 截断数组,移除多余元素
        this.data.length = writeIndex;
        return this;
    }

// 打印顺序表内容
    print() {
        console.log("顺序表:", this.data.join(", "));
    }
}

/* 链式线性表(链表)实现*/

class ListNode {
    constructor(value) {
        this.value = value;
        this.next = null;
    }
}

class LinkedList {
    constructor() {
        this.head = null;
        this.length = 0;
    }

// 从数组创建链表
    static fromArray(arr) {
        const list = new LinkedList();
        for (const value of arr) {
            list.append(value);
        }
        return list;
    }

// 添加节点到末尾
    append(value) {
        const newNode = new ListNode(value);

        if (!this.head) {
            this.head = newNode;
        } else {
            let current = this.head;
            while (current.next) {
                current = current.next;
            }
            current.next = newNode;
        }

        this.length++;
    }

// 删除所有负整数元素(保持相对顺序)
    removeNegatives() {
// 处理头节点为负的情况
        while (this.head && this.head.value < 0) {
            this.head = this.head.next;
            this.length--;
        }

        if (!this.head) return this;

        let prev = this.head;
        let current = this.head.next;

        while (current) {
            if (current.value < 0) {
// 跳过负值节点
                prev.next = current.next;
                this.length--;
            } else {
// 只移动prev指针当保留当前节点时
                prev = current;
            }
            current = current.next;
        }

        return this;
    }

// 打印链表值
    print() {
        const values = [];
        let current = this.head;
        while (current) {
            values.push(current.value);
            current = current.next;
        }
        console.log("链表:", values.join(" -> "));
    }
}

运行结果

=== 顺序线性表测试 === 原始数据: 顺序表: 1, 2, -1, -2, 3, -3 删除负整数后: 顺序表: 1, 2, 3 === 链式线性表测试 === 原始数据: 链表: 1 -> 2 -> -1 -> -2 -> 3 -> -3 删除负整数后: 链表: 1 -> 2 -> 3