/*
* @lc app=leetcode.cn id=707 lang=typescript
*
* [707] 设计链表
*/
// @lc code=start
//注意:采用ListNode命名可能会导致Duplicate identifier问题,这里懒得解决于是用小写了:)
//cur后面跟!因为是cur可定义为可空的值,但是使用的实际情况是不为空的,避免编译器提醒(看着烦
// !和?用法可以参考这篇文章
class listnode {
public val: number;
public next: listnode | null;
constructor(val?: number, next?: listnode | null) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
}
class MyLinkedList {
//链表长度
private size: number;
//头指针
private head: listnode | null;
//尾指针
private tail: listnode | null;
constructor() {
this.size = 0;
this.head = null;
this.tail = null;
}
//取节点函数
private getNode(index: number) {
//虚拟头结点法
let cur: listnode | null = new listnode(0, this.head);
for (let i = 0; i <= index; i++) {
cur = cur!.next;
}
return cur;
}
//获取第index个节点值
get(index: number): number {
if (index < 0 || index > this.size - 1) {
return -1;
} else {
let cur = this.getNode(index);
return cur!.val;
}
}
//头部添加新节点
addAtHead(val: number): void {
let node: listnode = new listnode(val, this.head);
this.head = node;
//若为空,更新尾指针
if (this.tail === null) {
this.tail = node;
}
this.size++;
}
//尾部添加新节点
addAtTail(val: number): void {
let node: listnode = new listnode(val, null);
if (this.tail) {
this.tail.next = node;
}
//若为空,则更新头指针
else {
this.head = node;
}
//更新尾指针
this.tail = node;
this.size++;
}
//在index处添加节点
addAtIndex(index: number, val: number): void {
if (index > this.size) {
return;
}
//头部插入新节点
if (index <= 0) {
this.addAtHead(val);
return;
}
//尾部插入新节点
if (index === this.size) {
this.addAtTail(val);
return;
}
//正常情况
let cur = this.getNode(index - 1);
let node = new listnode(val, cur!.next);
cur!.next = node;
this.size++;
}
deleteAtIndex(index: number): void {
if (index < 0 || index >= this.size) {
return;
}
//删除头节点
if (index === 0) {
this.head = this.head!.next;
//若节点数为1.更新尾指针
if (index === this.size - 1) {
this.tail = null;
}
this.size--;
return;
}
//正常情况处理
let cur = this.getNode(index - 1);
cur!.next = cur!.next!.next;
//若删除最后一个节点,更新尾指针
if (index === this.size - 1) {
this.tail = cur;
}
this.size--;
return;
}
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* var obj = new MyLinkedList()
* var param_1 = obj.get(index)
* obj.addAtHead(val)
* obj.addAtTail(val)
* obj.addAtIndex(index,val)
* obj.deleteAtIndex(index)
*/
// @lc code=end