链表
有序元素集合,逻辑上存在连续关系,物理上不需要连续存储
单向链表
type ListNode<T> = {
value: T
next: ListNode<T> | null
}
class LinkedListNode<T> implements ListNode<T> {
value: T
next: ListNode<T> | null
constructor(value:T){
this.value = value;
this.next = null;
}
}
class LinkedList<T> {
private head: ListNode<T> | null = null
private length: number = 0
constructor(headValue:T){
if(headValue !== undefined){
this.head = new LinkedListNode(headValue);
this.length ++;
}
}
getHead(){
return this.head;
}
size(){
return this.length;
}
append(nextValue:T):void {
if(this.head === null){
this.head = new LinkedListNode(nextValue);
}else{
let cur = this.head;
while(cur.next !== null){
cur = cur.next
}
cur.next = new LinkedListNode(nextValue);
}
this.length ++
}
remove(value:T){
if(this.head !== null){
if(this.head.value === value){
// let tmp = this.head
// this.head = tmp.next;
// tmp = null
// 注:手动释放
this.head = this.head.next;
// 注:JS自动内存回收机制会将原head指向的对象释放,可以不手动释放
this.length --
}