December 25, 2023
Linked List (bog'langan ro'yxat)
Linked List - bu data strukturalardan biri bo'lib undagi bir element o'zidan keyingi elementga linkni saqlaydi. Misol uchun:
const list = {
value: 1,
next: {
value: 0,
next: {
value: 3,
next: {
.......
}
}
}
}Yuqoridagi rasmda massiv va linked list ustida amallarning (o'qish, element qo'shish, o'chirish) bo'yicha tezligi keltirilgan.
Quyida linked listning bir elementini generatsiya qilib beradigan class keltirilgan:
class ListNode {
val: number
next: ListNode | null // keyingi element
constructor(val?: number, next?: ListNode | null) {
this.val = (val === undefined ? 0 : val)
this.next = (next === undefined ? null : next)
}
}Massivdagi sonlardan Linked List yasab chiqamiz:
const temp = [0, 1, 2, 3, 4, 5]
function generateLinkedList(arr: number[]): ListNode | null {
if (arr.length === 0) {
return null
}
const head = new ListNode(arr[0])
let current = head
for (let i = 1; i < arr.length; i++) {
const newNode = new ListNode(arr[i])
current.next = newNode
current = newNode
}
return head
}
const list = generateLinkedList(temp) //{val: 0, next: {val: 1, next: ...}}
class LinkedList {
head: ListNode | null
private _size: number // Linked Listning o'lchamini saqlaymiz.
constructor() {
this.head = new ListNode()
this._size = 0
}
// listni uzunligini qaytaradi
get size () {
return this._size
}
// kerakli indexga element qo'shish
insertAt(element: number, index: number) {
if (index < 0 || index > this.size) {
return console.log("Mavjud bo'lmagan index");
}
// Yangi node yaratib olamiz
let node = new ListNode(element)
let curr = this.head
let prev: ListNode | null = null
// Agar birinchi element bo'lsa
// ortiqcha sikl kerak emas
if (index == 0) {
node.next = this.head;
this.head = node;
} else {
curr = this.head;
let it = 0;
while (it < index) {
it++;
prev = curr;
curr = curr?.next || null;
}
// element qo'shish
node.next = curr;
prev!.next = node;
}
this._size++
}
}
To'liqroq ma'lumot olish uchun: https://www.freecodecamp.org/news/implementing-a-linked-list-in-javascript/
#linked_list #data_structure #algorithms
@elyor_dev