0% found this document useful (0 votes)
5 views11 pages

Linked List Basics-1

The document provides an overview of linked lists, including singly linked lists, doubly linked lists, and circular linked lists. It includes Python code examples for creating, inserting, deleting, and displaying nodes in these data structures. Additionally, it covers operations like adding polynomials using linked lists and reversing a singly linked list.

Uploaded by

Adarsh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views11 pages

Linked List Basics-1

The document provides an overview of linked lists, including singly linked lists, doubly linked lists, and circular linked lists. It includes Python code examples for creating, inserting, deleting, and displaying nodes in these data structures. Additionally, it covers operations like adding polynomials using linked lists and reversing a singly linked list.

Uploaded by

Adarsh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Linked List Basics

January 30, 2025

1 LINKED LISTS
1.0.1 Singly Linked List

[16]: class Node:


def __init__(self, data):
self.data = data
self.next = None

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

def http://localhost:8889/notebooks/Linked%20List%20Basics.
,→ipynb#insert_at_end(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node #if the node is first node
return
temp = self.head #Assign a temporary variable to traverse the list
while temp.next: #until temp.next!=None it will traverse the linked␣
,→list

temp = temp.next
temp.next = new_node

def display(self):
temp = self.head
while temp:
print(temp.data, end=" -> ")
temp = temp.next
print("None")

# Create a linked list and insert elements


ll = LinkedList()
ll.insert_at_end(10)
ll.insert_at_end(20)
ll.display()

1
10 -> 20 -> None

[17]: # Define the Node structure


class Node:
def __init__(self, data):
self.data = data # To Store data
self.next = None # Pointer to the next node

# Define the LinkedList class


class LinkedList:
def __init__(self):
self.head = None # Head of the list (initially empty)

# Insert at the beginning of the linked list


def insert_at_beginning(self, data):
new_node = Node(data) # Create a new node
new_node.next = self.head # Newly inserted node points to current head
self.head = new_node # Update head pinter with the address of new node

# Insert at the end of the linked list


def insert_at_end(self, data):
new_node = Node(data) # Create a new node
if self.head is None:
self.head = new_node # If list is empty, set head pointer to new␣
,→node

return
temp = self.head
while temp.next: # Traverse to the last node
temp = temp.next
temp.next = new_node # Link the last node to the new node

# Delete a node by value


def delete_node(self, key):
temp = self.head

# If head node itself holds the key


if temp is not None and temp.data == key:
self.head = temp.next # Change head
temp = None
return

# Search for the key to delete


prev = None
while temp is not None and temp.data != key:
prev = temp
temp = temp.next

2
if temp is None:
print(f"Element {key} not found in the list.")
return

prev.next = temp.next # Unlink the node from the list


temp = None

# Search for an element in the linked list


def search(self, key):
temp = self.head
while temp:
if temp.data == key:
return True # Element found
temp = temp.next
return False # Element not found

# Display the linked list elements


def traverse(self):
if self.head is None:
print("The linked list is empty.")
return
temp = self.head
while temp:
print(temp.data, end=" -> ")
temp = temp.next
print("None") # Indicating end of the list

# Create a LinkedList object and perform operations


ll = LinkedList()

# Insert elements
ll.insert_at_end(10)
ll.insert_at_end(20)
ll.insert_at_beginning(5)
ll.insert_at_end(30)

print("Linked List after insertions:")


ll.traverse()

# Delete an element
ll.delete_node(20)
print("Linked List after deletion of 20:")
ll.traverse()

# Search for an element


element = 10
if ll.search(element):

3
print(f"Element {element} found in the list.")
else:
print(f"Element {element} not found in the list.")

Linked List after insertions:


5 -> 10 -> 20 -> 30 -> None
Linked List after deletion of 20:
5 -> 10 -> 30 -> None
Element 10 found in the list.

[18]: # Insert in Beginning


# Node class to represent an element of the linked list
class Node:
def __init__(self, data):
self.data = data # Store data
self.next = None # Pointer to the next node

# LinkedList class to manage the list


class LinkedList:
def __init__(self):
self.head = None # Initially, the list is empty

# Function to insert a new node at the beginning


def insert_at_beginning(self, value):
new_node = Node(value) # Step 2: Create new node
new_node.next = self.head # Step 5: Link new node to existing list
self.head = new_node # Step 6: Update head to point to new node

# Function to display the linked list


def display(self):
temp = self.head
while temp:
print(f"{temp.data} ->", end=" ")
temp = temp.next
print("NULL")

ll = LinkedList()
ll.insert_at_beginning(9)
ll.insert_at_beginning(5)
ll.insert_at_beginning(10)

print("Linked List after inserting elements at the beginning:")


ll.display()

Linked List after inserting elements at the beginning:


10 -> 5 -> 9 -> NULL

4
[1]: #Adding two polynomials

# Class representing a term in a polynomial


class Node:
def __init__(self, coeff, power):
self.coeff = coeff # Coefficient of the term
self.power = power # Exponent of the term
self.next = None # Pointer to the next term

# Class to represent a polynomial using a linked list


class PolynomialLinkedList:
def __init__(self):
self.head = None # Initialize an empty polynomial

# Function to insert a new term in sorted order by power (descending)


def insert_term(self, coeff, power):
new_node = Node(coeff, power)

# If the list is empty or the new term has a greater power than the head
if self.head is None or self.head.power < power:
new_node.next = self.head
self.head = new_node
return

temp = self.head
while temp.next and temp.next.power > power:
temp = temp.next

# If the same power term exists, add coefficients


if temp.next and temp.next.power == power:
temp.next.coeff += coeff
else:
new_node.next = temp.next
temp.next = new_node

# Function to display the polynomial


def display(self):
if self.head is None:
print("0")
return
temp = self.head
while temp:
print(f"{temp.coeff}x^{temp.power}", end="")
if temp.next:
print(" + ", end="")
temp = temp.next
print()

5
# Function to add two polynomials
@staticmethod
def add_polynomials(poly1, poly2):
p1 = poly1.head
p2 = poly2.head
result = PolynomialLinkedList()

while p1 and p2:


if p1.power > p2.power:
result.insert_term(p1.coeff, p1.power)
p1 = p1.next
elif p1.power < p2.power:
result.insert_term(p2.coeff, p2.power)
p2 = p2.next
else: # Powers are equal, sum coefficients
sum_coeff = p1.coeff + p2.coeff
if sum_coeff != 0:
result.insert_term(sum_coeff, p1.power)
p1 = p1.next
p2 = p2.next

# If there are remaining terms in poly1


while p1:
result.insert_term(p1.coeff, p1.power)
p1 = p1.next

# If there are remaining terms in poly2


while p2:
result.insert_term(p2.coeff, p2.power)
p2 = p2.next

return result

# Example usage
poly1 = PolynomialLinkedList()
poly1.insert_term(3, 2)
poly1.insert_term(5, 1)
poly1.insert_term(6, 0)

print("Polynomial 1:")
poly1.display()

poly2 = PolynomialLinkedList()
poly2.insert_term(4, 2)
poly2.insert_term(2, 1)
poly2.insert_term(8, 0)

6
print("Polynomial 2:")
poly2.display()

# Add the two polynomials


result_poly = PolynomialLinkedList.add_polynomials(poly1, poly2)
print("Sum of the two polynomials:")
result_poly.display()

Polynomial 1:
3x^2 + 5x^1 + 6x^0
Polynomial 2:
4x^2 + 2x^1 + 8x^0
Sum of the two polynomials:
7x^2 + 7x^1 + 14x^0

[ ]: #Deletion
def delete_head(self):
if self.head is None:
print("List is empty.")
return
self.head = self.head.next # Move head to the next node

#Delete node from end of the linked list


def delete_tail(self):
if self.head is None:
print("List is empty.")
return
if self.head.next is None: # Only one node in the list
self.head = None
return

temp = self.head
while temp.next.next is not None:
temp = temp.next

temp.next = None # Remove reference to the last node

#Delete a node at specific position


def delete_by_value(self, value):
# Check if the list is empty
if self.head is None:
print("List is empty.")
return

# If the head node contains the value to be deleted


if self.head.data == value:

7
self.head = self.head.next # Move head to the next node
return

# Traverse the list to find the node with the specified value
temp = self.head
while temp.next and temp.next.data != value:
temp = temp.next

# If the value is not found


if temp.next is None:
print("Value not found.")
else:
# Skip the node containing the value
temp.next = temp.next.next

[ ]: #Double linked list

class Node:
def __init__(self, data):
self.data = data # The value/data stored in the node
self.next = None # Pointer to the next node
self.prev = None # Pointer to the previous node
#insert in beginning
class DoublyLinkedList:
def __init__(self):
self.head = None

def insert_at_beginning(self, value):


new_node = Node(value)

if self.head is not None:


self.head= new_node

new_node.next = self.head
self.head = new_node

#insert in end of DLL


def insert_at_end(self, value):
new_node = Node(value)

if self.head is None:
self.head = new_node
return

last = self.head
while last.next:
last = last.next

8
last.next = new_node
new_node.prev = last

[1]: #Reverse a single linked list


class Node:
def __init__(self, data):
self.data = data # Store data of the node
self.next = None # Pointer to the next node, initially None

class SinglyLinkedList:
def __init__(self):
self.head = None # Initially, the list is empty
self.tail = None # Initially, there is no tail

def addNode(self, data):


new_node = Node(data) # Create a new node with the given data

if self.head is None: # If the list is empty


self.head = new_node # Set head to the new node
self.tail = new_node # Set tail to the new node as well
else:
self.tail.next = new_node # Link the last node's next to the new␣
node
,→

self.tail = new_node # Update the tail to the new node

def reverse(self, current):


if current is None: # Base case: End of list
return
self.reverse(current.next) # Recursive call to reverse the rest of the␣
,→list

print(current.data, end=" ") # Print data after the recursive call␣


,→(this ensures reverse order)

def display(self):
current = self.head # Start from the head of the list
while current: # Traverse the list until current is None
print(current.data, end=" ") # Display the data of the current node
current = current.next # Move to the next node
print() # For a new line after displaying the list

# Example usage:
sll = SinglyLinkedList() # Create an instance of SinglyLinkedList

# Add nodes to the list


sll.addNode(10)
sll.addNode(20)

9
sll.addNode(30)
sll.addNode(40)

# Display the list


print("Original List:")
sll.display()

# Display the list in reverse order


print("Reversed List:")
sll.reverse(sll.head) # Start reversing from the head

Original List:
10 20 30 40
Reversed List:
40 30 20 10

[1]: #Circular linked list

class Node:
def __init__(self, data):
self.data = data
self.next = None

class CircularLinkedList:
def __init__(self):
self.head = None

def insert(self, data):


new_node = Node(data)

# If the list is empty, initialize the first node


if not self.head:
self.head = new_node
self.head.next = self.head # Point to itself
return

# Traverse to the last node


temp = self.head
while temp.next != self.head:
temp = temp.next

# Insert the new node at the end


temp.next = new_node
new_node.next = self.head

# Display the circular linked list

10
def display(self):
if not self.head:
print("List is empty")
return

temp = self.head
while True:
print(temp.data, end=" -> ")
temp = temp.next
if temp == self.head:
break
print("... (circular)")

# Example Usage
cll = CircularLinkedList()

# Insert elements sequentially into the circular linked list


cll.insert(10)
cll.insert(20)
cll.insert(30)
cll.insert(40)

# Display the list


cll.display() # Output: 10 -> 20 -> 30 -> 40 -> ... (circular)

10 -> 20 -> 30 -> 40 -> … (circular)

[ ]:

11

You might also like