Skip to content

Instantly share code, notes, and snippets.

@QuocCao-dev
Last active November 20, 2022 10:11
Show Gist options
  • Save QuocCao-dev/7a40a6e8b5aae2b2ed264a316e791f48 to your computer and use it in GitHub Desktop.
Save QuocCao-dev/7a40a6e8b5aae2b2ed264a316e791f48 to your computer and use it in GitHub Desktop.
class NodeClass {
val: string;
next: NodeClass | null;
constructor(val: string) {
this.val = val;
this.next = null;
}
}
class SinglyLinkedList {
head: NodeClass | null;
tail: NodeClass | null;
length: number;
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
// thêm một Node mới với data là val vào cuối linked list
push(val: string) {
let newNode = new NodeClass(val);
// nếu linked list chưa có phần tử nào
if (!this.head) {
this.head = newNode;
this.tail = this.head;
} else {
this.tail!.next = newNode;
this.tail = newNode;
}
this.length++;
return this;
}
// xoá phần tử cuối của linked list
pop() {
// nếu list không có phần tử nào thì return undefined
if (!this.head) return undefined;
let current = this.head; // current để tìm phần tử tail
let newTail = current; // newTail chính là cái prev
while (current.next) {
newTail = current;
current = current.next;
}
this.tail = newTail;
this.tail.next = null;
this.length--;
if (this.length === 0) {
this.head = null;
this.tail = null;
}
return current;
}
// xoá phần tử đầu tiên của linked list
shift() {
// kiểm tra nếu list không có phần tử nào thì return
if (!this.head) return;
let tmp = this.head;
this.head = tmp.next;
this.length--;
if (this.length === 0) {
this.tail = null;
}
return tmp;
}
// thêm một Node mới với data là val vào đầu linked list
unshift(val: string) {
let newNode = new NodeClass(val);
if (!this.head) {
this.head = newNode;
this.tail = this.head;
} else {
newNode.next = this.head;
this.head = newNode;
}
this.length++;
return this;
}
// trả về Node ở vị trí index
get(index: number) {
if (index < 0 || index >= this.length) return null;
let counter = 0;
let current = this.head;
while (counter !== index && current) {
current = current.next;
counter++;
}
return current;
}
set(index: number, val: string) {
let foundNode = this.get(index);
if (foundNode) {
foundNode.val = val;
return true;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment