js 列表实现
JavaScript 列表实现方法
在 JavaScript 中,列表通常通过数组或特定数据结构实现。以下是几种常见的实现方式:
使用原生数组
JavaScript 数组自带多种列表操作方法,适合大多数场景:

const list = [1, 2, 3];
list.push(4); // 尾部添加
list.pop(); // 尾部移除
list.unshift(0); // 头部添加
list.shift(); // 头部移除
链表实现
需要更灵活的操作时可实现链表结构:

class ListNode {
constructor(val) {
this.val = val;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.size = 0;
}
addAtTail(val) {
const node = new ListNode(val);
if (!this.head) this.head = node;
else {
let current = this.head;
while (current.next) current = current.next;
current.next = node;
}
this.size++;
}
}
双向链表实现
需要双向遍历时可扩展为双向链表:
class DoublyListNode {
constructor(val) {
this.val = val;
this.prev = null;
this.next = null;
}
}
class DoublyLinkedList {
constructor() {
this.head = null;
this.tail = null;
this.size = 0;
}
addAtTail(val) {
const node = new DoublyListNode(val);
if (!this.head) this.head = node;
else {
node.prev = this.tail;
this.tail.next = node;
}
this.tail = node;
this.size++;
}
}
性能优化建议
- 频繁插入/删除操作时优先考虑链表结构
- 随机访问需求高时使用原生数组
- 大数据量时注意链表的内存开销
实用工具方法
扩展数组功能实现类 List 操作:
class List {
constructor(items = []) {
this.items = [...items];
}
add(item) {
this.items.push(item);
}
remove(index) {
return this.items.splice(index, 1)[0];
}
get(index) {
return this.items[index];
}
}






