Chapter 2 Linked List DSA Notes
Chapter 2 Linked List DSA Notes
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
Cons:
Memory Overhead: Each node requires extra memory for storing the reference to the
next node.
Access Time: Accessing elements is slower than arrays because nodes must be
accessed sequentially (no direct access by index).
Complexity: More complex than arrays in terms of implementation and debugging.
Python Function
# insert new node at front of list
def insertfront(self, data):
#create a new node
newnode =sllnode(data)
newnode.next=self.head
self.head=newnode
2. Insert at End (Insert a node at the end of the list)
Algorithm:
Step 1: Create a new node.
Step 2: If the list is empty, set the head to the new node.
Step 3: Traverse the list until the last node (where next is NULL).
Step 4: Set the next pointer of the last node to the new node.
Prof. Lokhande D.B.
Python Function
# insert new node at end of list
def insertend(self, data):
#create a new node
newnode =sllnode(data)
#checks if the list is empty
if(self.head == none):
#if list is empty, then head will point to new node
self.head = newnode
else:
#start out looking at the first node
current=self.head
while current.next is not none:
current=current.next
#assign current node to next of newnode
current.next=newnode
Python Function
def search(self, key):
current = self.head
while current:
if current.data == key:
Prof. Lokhande D.B.
return True
current = current.next
return False
Python Function
def traverse(self):
current = self.head
while current:
print(current.data)
current = current.next
print("None")
9. Find Length of the List (Count the number of nodes in the list)
Algorithm:
1. Initialize a counter to zero.
2. Traverse the list, incrementing the counter for each node.
3. Return the counter as the length of the list.
Python Function
def find_length(self):
length = 0
current = self.head
while current:
length += 1
current = current.next
return length
2. Insertion at End
Step 1: Create a new node.
Step 2: Traverse the list to find the last node.
Step 3: Update the next pointer of the last node to point to the new node.
Step 4: Make the new node point to the head.
return
#find the position
current=self.head
for i in range(1,pos-1):
if current current.next is none:
print(“position out of bound”)
current=current.next
#insert tne node
newnode.next= current.next
current.next=newnode
class Node:
def __init__(self, data):
self.data = data # Data in the node
self.next = None # Pointer to the next node
self.prev = None # Pointer to the previous node
class DoublyLinkedList:
def __init__(self):
self.head = None # Initialize head as None (empty list)
newnode.prev = current # Set the new node's prev to the last node
else:
self.head=self.head.next
self.head.prev=none