01.移除链表元素
思路:设置虚拟头节点,采用前后节点的方式遍历链表。虚拟头节点为前一位,链表首位为当前节点。遍历过程中,如果当前节点的值等于val,就将前节点的next指向当前节点的next。
function removeElements(head: ListNode | null, val: number): ListNode | null {
// 设置虚拟头节点
const tmpNode:ListNode | null = new ListNode(0, head)
// 前节点为虚拟头节点
let prev:ListNode = tmpNode
// 当前节点为链表首位
let cur:ListNode = prev.next
while (cur) {
if (cur.val == val) {
prev.next = cur.next
} else {
prev = cur
}
cur = cur.next
}
return tmpNode.next
};
02.设计链表
思路:创建一个私有方法getNode,用于获取第n位节点
class MyLinkedList {
private length:number;
private head:ListNode | null;
private tail:ListNode | null;
constructor() {
this.length = 0;
this.head = null;
this.tail = null;
}
get(index: number): number {
if (index < 0 || index >= this.length) {
return -1
}
const cur = this.getNode(index);
return cur.val
}
addAtHead(val: number): void {
const first = new ListNode(val, this.head)
this.head = first
if (!this.tail) {
this.tail = first
}
this.length++
}
addAtTail(val: number): void {
const tail:ListNode = new ListNode(val)
if (this.tail) {
this.tail.next = tail
} else {
this.head = tail
}
this.tail = tail
this.length++
}
addAtIndex(index: number, val: number): void {
if (index > this.length) return
if (index == this.length) {
this.addAtTail(val)
return
}
if (index == 0) {
this.addAtHead(val)
return
}
const tmp = this.getNode(index - 1)
const newNode = new ListNode(val, tmp.next)
tmp.next = newNode;
this.length++
}
deleteAtIndex(index: number): void {
if (index >= this.length) return
if (index == 0) {
this.head = this.head!.next
if (index === this.length - 1) {
this.tail = null
}
this.length--
return
}
const cur = this.getNode(index - 1)
cur.next = cur.next!.next
if (index == this.length - 1) {
this.tail = cur
}
this.length--
}
private getNode (index:number):ListNode {
let cur:ListNode = new ListNode(0, this.head);
for (let i = 0; i <= index; i++) {
cur = cur.next!
}
return cur
}
}