抽象描述
线性表:由大于等于0个元素构成的有序序列
存储实现
数组存储实现
- 利用数组连续存储空间顺序存放线性表元素
class List<T> {
private items:T[]
// 初始化空线性表
constructor(){
this.items = []
}
//返回线性表长度
size():number {
return this.items.length;
}
// 在线性表中指定位置插入指定元素
insert(position:number, element:T):T[] {
const length = this.items.length;
if(position <= length && position >= 0){
for(var i = length; i > position; i--){
this.items[i] = this.items[i - 1]
}
this.items[position] = element
}
return this.items
}
// T(n) = O(n)
// 在线性表中查找指定元素第一次出现的位置
find(element:T):number {
let position = 0;
const length = this.items.length;
while(position < length && this.items[position] !== element){
position++;
}
if(position < length){
return position
}
return -1
}
// T(n) = O(n)
// 在线性表中查找指定位置的元素
findAt(position:number):T|void {
const length = this.items.length;
if(position < length && position >= 0){
return this.items[position]
}
}
// 在线性表中删除指定位置的元素
remove(position:number):T[] {
const length = this.items.length;
if(position < length && position >= 0){
for(var i = position; i < length - 1; i++){
this.items[i] = this.items[i + 1]
}
this.items.length --
// 注:设置数组length属性截断数组是JS中惟一非遍历缩短数组长度方法
}
return this.items
}
// T(n) = O(n)
}
链表存储实现
- 不要求逻辑相邻元素物理存储相邻,利用链表实现线性表元素逻辑关系
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
constructor(){
this.head = null;
}
// 返回线性表长度
size():number{
let length = 0
let cur = this.head
while(cur !== null){
cur = cur.next
length ++
}
return length
}
// T(n) = O(n)
//在线性表中指定位置插入指定元素
insert(position:number, element:T):ListNode<T> {
if(position === 0){
const node = new LinkedListNode(element);
node.next = this.head;
this.head = node
return this.head
}
let index = 1;
var cur = this.head
while(index !== position && cur !== null){
cur = cur.next
index++
}
if(index === position){
const node = new LinkedListNode(element)
node.next = cur.next
cur.next = node
}
return this.head
}
// T(n) = O(n)
// 在线性表中查找指定元素第一次出现的位置
find(element:T):number {
let position = 0;
let cur = this.head
while(cur !== null && cur.value !== element){
cur = cur.next
position++
}
if(cur.value === element){
return position
}else{
return -1
}
}
// T(n) = O(n)
//在线性表中查找指定位置的元素
findAt(position:number):T | void {
let index = 0;
let cur = this.head
while(index !== position && cur !== null){
cur = cur.next
index++
}
if(index === position){
return cur.value
}
}
// T(n) = O(n)
// 在线性表中删除指定位置的元素
remove (position:number):ListNode<T> {
if(position === 0){
let target = this.head ;
this.head = this.head.next
target = null
// 注:通常来说,执行删除元素操作,必须释放删除元素内存
// 对于JS/TS来说,内存回收机制会自动清理不再被引用的元素对象,故此操作不是必须的
return this.head
}
let index = 1;
var cur = this.head ;
while(index !== position && cur !== null){
cur = cur.next
index++
}
if(index === position){
let target = cur.next;
cur.next = cur.next.next
target = null
}
return this.head
}
// T(n) = O(n)
}