0% found this document useful (0 votes)
8 views

LAB - Python 01

Uploaded by

AarishBangash
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

LAB - Python 01

Uploaded by

AarishBangash
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 10

LAB – Python 01

28/12/23
Introduction to Linked Lists

• A linked list is a data structure consisting of a sequence of elements


where each element points to the next element in the sequence.
• Unlike arrays, linked lists do not have a fixed size, and memory is
allocated dynamically as elements are added.
Basic Structure of a Node

• class Node:
• def __init__(self, data):
• self.data = data
• self.next = None
Creating a Linked List

• class LinkedList:
• def __init__(self):
• self.head = None

• def append(self, data):


• new_node = Node(data)
• if not self.head:
• self.head = new_node
• else:
• current = self.head
• while current.next:
• current = current.next
• current.next = new_node
Displaying a Linked List

• def display(self):
• current = self.head
• while current:
• print(current.data, end=" -> ")
• current = current.next
• print("None")
Insertion at the Beginning

• def insert_at_beginning(self, data):


• new_node = Node(data)
• new_node.next = self.head
• self.head = new_node
Insertion at a Specific Position

• def insert_at_position(self, position, data):


• if position == 0:
• self.insert_at_beginning(data)
• else:
• new_node = Node(data)
• current = self.head
• for _ in range(position - 1):
• if current is None:
• print("Position out of bounds.")
• return
• current = current.next
• new_node.next = current.next
• current.next = new_node
Deletion at the Beginning

• def delete_at_beginning(self):
• if self.head:
• self.head = self.head.next
• else:
• print("List is empty. Nothing to delete.")
Deletion at a Specific Position
• def delete_at_position(self, position):
• if position == 0:
• self.delete_at_beginning()
• else:
• current = self.head
• for _ in range(position - 1):
• if current is None or current.next is None:
• print("Position out of bounds.")
• return
• current = current.next
• current.next = current.next.next
Thank You

You might also like