1
0
Fork 0
Obsidian 管理的个人笔记仓库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
1.6 KiB

## 数组转换成链表
```typescript
interface LinkedList {
value: Number | null;
next: LinkedList | null;
}
const toLinkedList = (array: Number[]): LinkedList => {
let linkedList: LinkedList = {
value: null,
next: null,
};
const endLength = array.length - 1;
for (let index = endLength; index >= 0; index--) {
linkedList = {
value: array[index],
next: index === endLength ? null : linkedList,
};
}
return linkedList;
};
```
## 反转单向链表
```typescript
interface LinkedList {
value: Number | null;
next: LinkedList | null;
}
const reverseLinkedList = (LinkedList: LinkedList) => {
let preNode: LinkedList | null = null;
let curNode: LinkedList | null = LinkedList;
let nexNode: LinkedList | null = LinkedList.next;
while (curNode) {
curNode.next = preNode;
preNode = curNode;
if (nexNode == null) break;
curNode = nexNode;
nexNode = nexNode.next;
}
return curNode;
};
```
## 使用链表实现队列
```typescript
interface LinkedList {
value: number | null;
next: LinkedList | null;
}
class LinkedListQueue {
private head: LinkedList | null = null;
private tail: LinkedList | null = null;
private len: number = 0;
add(value: number) {
if (this.len === 0) {
this.head = { value, next: null };
this.tail = this.head;
this.len++;
return;
}
this.tail.next = { value, next: null };
this.tail = this.tail.next;
this.len++;
}
pop(): number {
if (!this.head || !this.tail) return;
const popValue = this.head.value;
this.head = this.head.next;
this.len--;
return popValue;
}
get length() {
return this.len;
}
}
```