707. Design Linked List

202410090948
tags: #linked-list

class ListNode {
	constructor(val) {
		this.val = val;
		this.prev = null;
		this.next = null;
	}
}

var MyLinkedList = function() {
	this.first = new ListNode(0);
	this.last = new ListNode(0);
	this.first.next = this.last;
	this.last.prev = this.first;
	this.len = 0;
};

MyLinkedList.prototype.get = function(index) {
	if (index < 0 || index >= this.len) {
		return -1;
	}
	let cur = this.first;
	for (let i = 0; i < index; i++) {
		cur = cur.next;
	}
	return cur.next.val;
};

MyLinkedList.prototype.addAtHead = function(val) {
	this.addAtIndex(0, val);
};

MyLinkedList.prototype.addAtTail = function(val) {
	this.addAtIndex(this.len, val);
};

MyLinkedList.prototype.addAtIndex = function(index, val) {
	if (index < 0 || index > this.len) {
		return;
	}
	let cur = this.first;
	for (let i = 0; i < index; i++) {
		cur = cur.next;
	}
	const newNode = new ListNode(val);
	const nextNode = cur.next;
	cur.next = newNode;
	newNode.next = nextNode;
	nextNode.prev = newNode;
	newNode.prev = this.first;
	this.len += 1;
};

MyLinkedList.prototype.deleteAtIndex = function(index) {
	if (this.len === 0 || index < 0 || index >= this.len) {
		return;
	}
	let cur = this.first;
	for (let i = 0; i < index; i++) {
		cur = cur.next;
	}
	cur.next = cur.next.next;
	this.len -= 1;
};

Reference

https://leetcode.com/problems/design-linked-list/