线性表操作演示

            
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(", "));
        const resultDiv = document.getElementById('result');
        resultDiv.innerHTML += `顺序表: ${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 = 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(" -> ")); const resultDiv = document.getElementById('result'); resultDiv.innerHTML += `链表: ${values.join(" -> ")}
`; } } const testArray = [1, 2, -1, -2, 3, -3]; console.log("=== 顺序线性表测试 ==="); const resultDiv = document.getElementById('result'); resultDiv.innerHTML += "=== 顺序线性表测试 ===
"; const seqList = new SequentialList(testArray); console.log("原始数据:"); resultDiv.innerHTML += "原始数据:
"; seqList.print(); seqList.removeNegatives(); console.log("删除负整数后:"); resultDiv.innerHTML += "删除负整数后:
"; seqList.print(); console.log("\n=== 链式线性表测试 ==="); resultDiv.innerHTML += "
=== 链式线性表测试 ===
"; const linkedList = LinkedList.fromArray(testArray); console.log("原始数据:"); resultDiv.innerHTML += "原始数据:
"; linkedList.print(); linkedList.removeNegatives(); console.log("删除负整数后:"); resultDiv.innerHTML += "删除负整数后:
"; linkedList.print();
返回主页