لیست پیوندی یه نوع ساختار داده یا Data Structure. کارش ذخیره کردن داده ها به صورت زنجیرهای. به هر پیوند یا زنجیر Node میگیم. این node ها آدرس node بعدیشون رو میدونن. مثل صف نونوایی میمونه که شما همیشه یادتون نگه میدارین که پشت سر کی هستین تا صف رو گم نکنین 😁
کاربرد
زمانی که نمیدونین تعداد داده هاتون چقدر هست
زمانی که میخواین داده هارو مرحله به مرحله یا تکی تکی به لیست اضافه کنین
وقتی که بخواین یه داده ای رو به وسط لیست اضافه یا حذف کنین
یکی از نکات مثبت لیست پیوندی سرعت بالای اضافه کردن یه آیتم جدید بهش هست. برخلاف آرایه که موقع اضافه کردن داده جدید، دوباره ساخته میشه، اینجا فقط یه پیوند به داده جدید میخوره.
پیاده سازی لیست پیوندی یا linked list در پایتون
class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self, head=None): self.head = head def append(self, new_node): current = self.head if current: while current.next: current = current.next current.next = new_node else: self.head = new_node def delete(self, value): current = self.head if current.value == value: self.head = current.next else: while current: if current.value == value: break prev = current current = current.next if current is None: return prev.next = current.next current = None def insert(self, new_element, position): count = 1 current = self.head if position == 1: new_element.next = self.head self.head = new_element while current: if count + 1 == position: new_element.next = current.next current.next = new_element return else: count += 1 current = current.next pass def print(self): current = self.head while current: print(current.value) current = current.next n1 = Node(2) n2 = Node(4) n3 = Node(6) n4 = Node(8) myList = LinkedList(n1) myList.append(n3) myList.insert(n2, 2) myList.append(n4) myList.delete(8) myList.print()