In my TypeScript code, I have a Linked List class that is working perfectly. The class includes a Node type and functions to add items to the list.
type ListItem = number | string | object;
class Node {
private value: ListItem;
private next: Node | null;
constructor(value: ListItem) {
this.value = value;
this.next = null;
}
set nodeValue(value: ListItem) {
this.value = value;
}
set nextNode(next: Node | null) {
this.next = next;
}
get nodeValue(): ListItem {
return this.value;
}
get nextNode(): Node | null {
return this.next;
}
}
export class LinkedList {
private head: Node | null;
private tail: Node | null;
constructor(value: ListItem | null = null) {
if (value) {
const node = new Node(value);
this.head = node;
this.tail = node;
} else {
this.head = null;
this.tail = null;
}
}
public addLast(item: ListItem): void {
const newNode = new Node(item);
if (this.head === null || this.tail == null) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.nextNode = newNode;
this.tail = this.tail.nextNode;
}
}
public addFirst(item: ListItem): void {
const newNode = new Node(item);
if (this.head === null || this.tail === null) {
this.head = newNode;
this.tail = newNode;
} else {
newNode.nextNode = this.head;
this.head = newNode;
}
}
}
To make sure the Linked List is not empty before adding an item, I introduced an isEmpty() function as shown below.
private isEmpty(): boolean {
return this.head === null || this.tail === null;
}
I then updated the addLast() function to use the isEmpty() function for checking if the list is empty.
public addLast(item: ListItem): void {
const newNode = new Node(item);
if (this.isEmpty()) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.nextNode = newNode; // error
this.tail = this.tail.nextNode; // error
}
}
However, this change resulted in an error because TypeScript cannot infer that the properties this.tail and this.head are no longer null within the else statement. Is there a way to address this issue without compromising the implementation? Perhaps through a type guard or some other technique? Any advice would be appreciated as I am still learning TypeScript.