/* 顺序线性表(数组)实现*/
class SequentialList {
constructor(array = []) {
this.data = [...array];
}
// 查找最后一个最小值的索引
findLastMinIndex() {
if (this.data.length === 0) return -1;
let minValue = this.data[0];
let lastMinIndex = 0;
for (let i = 1; i < this.data.length; i++) {
if (this.data[i] <= minValue) {
minValue = this.data[i];
lastMinIndex = i;
}
}
return lastMinIndex;
}
// 打印顺序表内容
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++;
}
// 查找最后一个最小值的节点索引
findLastMinIndex() {
if (!this.head) return -1;
let minValue = this.head.value;
let lastMinIndex = 0;
let current = this.head;
let index = 0;
while (current) {
if (current.value <= minValue) {
minValue = current.value;
lastMinIndex = index;
}
current = current.next;
index++;
}
return lastMinIndex;
}
// 打印链表值
print() {
const values = [];
let current = this.head;
while (current) {
values.push(current.value);
current = current.next;
}
console.log("链表:", values.join(" -> "));
}
}
/* 测试代码*/
const testArray = [1, 5, 1, 1, 3, 2, 4];
console.log("=== 顺序线性表测试 ===");
const seqList = new SequentialList(testArray);
seqList.print();
console.log("最后一个最小值的索引:", seqList.findLastMinIndex());
console.log("\n=== 链式线性表测试 ===");
const linkedList = LinkedList.fromArray(testArray);
linkedList.print();
console.log("最后一个最小值的索引:", linkedList.findLastMinIndex());
=== 顺序线性表测试 ===
顺序表: 1, 5, 1, 1, 3, 2, 4
最后一个最小值的索引: 3
=== 链式线性表测试 ===
链表: 1 -> 5 -> 1 -> 1 -> 3 -> 2 -> 4
最后一个最小值的索引: 3