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

aws

aws

Uploaded by

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

aws

aws

Uploaded by

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

single linked list

A Singly Linked List is a type of linked list where each node contains two parts:

1. Data: The actual value that the node holds.


2. Next: A pointer or reference to the next node in the list.

In a singly linked list, each node points to the next node, and the last node points to None
(indicating the end of the list). It only allows traversal in one direction, from the head (first node)
to the last node.

Singly Linked List Operations

We can perform the following operations on a singly linked list:

1. Insert at the beginning: Add a node to the front of the list.


2. Insert at the end: Add a node to the end of the list.
3. Delete a node: Remove a node with a given value.
4. Display the list: Print all the nodes in the list.
5. Search for a node: Find if a node with a given value exists in the list.

Singly Linked List Implementation in Python

1. Define a Node Class

Each node will have two attributes:

 data: Stores the value of the node.


 next: Points to the next node (or None if it is the last node).

python
Copy code
class Node:
def __init__(self, data):
self.data = data # The value of the node
self.next = None # Pointer to the next node (initialized to None)

2. Define the Singly Linked List Class

The LinkedList class manages the list with various operations:

python
Copy code
class LinkedList:
def __init__(self):
self.head = None # Initially, the list is empty (head is None)
# 1. Insert a new node at the beginning
def prepend(self, data):
new_node = Node(data) # Create a new node
new_node.next = self.head # Point the new node to the current head
self.head = new_node # Make the new node the head of the list

# 2. Insert a new node at the end


def append(self, data):
new_node = Node(data) # Create a new node
if self.head is None: # If the list is empty, the new node is the
head
self.head = new_node
return
# Otherwise, traverse to the last node and add the new node
current = self.head
while current.next:
current = current.next
current.next = new_node # Set the last node's next pointer to the new
node

# 3. Display the entire list


def display(self):
current = self.head
while current:
print(current.data, end=" -> ") # Print the node's data
current = current.next
print("None") # End of the list

# 4. Delete a node by its value


def delete(self, key):
current = self.head
# If the node to be deleted is the head node
if current and current.data == key:
self.head = current.next # Move the head pointer to the next node
current = None # Free the node
return

# Traverse the list to find the node to delete


prev = None
while current and current.data != key:
prev = current
current = current.next

# If the node wasn't found


if current is None:
print("Node not found")
return

# Unlink the node from the list


prev.next = current.next
current = None # Free the node

# 5. Search for a node by value


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

Example Usage

Now, let's see how we can use this LinkedList class to perform various operations.

python
Copy code
# Create a LinkedList object
ll = LinkedList()

# Add nodes to the linked list


ll.append(10) # Add 10 at the end
ll.append(20) # Add 20 at the end
ll.append(30) # Add 30 at the end

# Display the list


ll.display() # Output: 10 -> 20 -> 30 -> None

# Add node at the beginning


ll.prepend(5) # Add 5 at the beginning

# Display the list again


ll.display() # Output: 5 -> 10 -> 20 -> 30 -> None

# Delete a node
ll.delete(20) # Delete the node with value 20
ll.display() # Output: 5 -> 10 -> 30 -> None

# Search for a node


print(ll.search(10)) # Output: True (since 10 exists)
print(ll.search(100)) # Output: False (since 100 does not exist)

Explanation of Operations

1. prepend(data): Adds a new node with the given data at the beginning of the list.
o Creates a new node and sets its next pointer to the current head.
o Updates the head to the new node.

2. append(data): Adds a new node with the given data at the end of the list.
o Traverses the list to find the last node, and then sets the next pointer of the last node
to the new node.

3. display(): Prints the list in a readable format.


o Traverses the list, printing each node's data followed by an arrow (->), ending with
None.
4. delete(key): Deletes the first node with the given key.
o If the node to delete is the head, it updates the head pointer.
o Otherwise, it finds the node and adjusts the next pointer of the previous node to skip
the node being deleted.

5. search(key): Searches for a node with the given key.


o Traverses the list, returning True if a node with the specified value is found, otherwise
returns False.

Advantages of Singly Linked Lists

 Dynamic Size: No fixed size, and elements can be added or removed easily.
 Efficient Insertions/Deletions: Inserting or deleting nodes, especially at the beginning, is
efficient.

Disadvantages

 Slow Access Time: To access a specific node, we have to traverse the list from the head to the
desired node.
 Extra Memory: Each node needs extra memory to store the pointer to the next node.

Let me know if you'd like to dive deeper into any part of the singly linked list or have more
questions!

4o mini

You said:
name 'LinkedList' is not defined showing error

ChatGPT said:

ChatGPT

The error name 'LinkedList' is not defined usually occurs when Python doesn't recognize
the class LinkedList because it's either not defined or there's an issue with the code ordering.

To fix this error, ensure that:

1. You have defined the LinkedList class before you create an instance of it.
2. The code is in the correct order, meaning the class definition should come first, followed by your
code that uses the class.

Here is a complete working example that you can run without issues:
Full Code Example (Singly Linked List):
python
Copy code
# Node class definition
class Node:
def __init__(self, data):
self.data = data # The value of the node
self.next = None # Pointer to the next node (initialized to None)

# LinkedList class definition


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

# 1. Insert a new node at the beginning


def prepend(self, data):
new_node = Node(data) # Create a new node
new_node.next = self.head # Point the new node to the current head
self.head = new_node # Make the new node the head of the list

# 2. Insert a new node at the end


def append(self, data):
new_node = Node(data) # Create a new node
if self.head is None: # If the list is empty, the new node is the
head
self.head = new_node
return
# Otherwise, traverse to the last node and add the new node
current = self.head
while current.next:
current = current.next
current.next = new_node # Set the last node's next pointer to the new
node

# 3. Display the entire list


def display(self):
current = self.head
while current:
print(current.data, end=" -> ") # Print the node's data
current = current.next
print("None") # End of the list

# 4. Delete a node by its value


def delete(self, key):
current = self.head
# If the node to be deleted is the head node
if current and current.data == key:
self.head = current.next # Move the head pointer to the next node
current = None # Free the node
return

# Traverse the list to find the node to delete


prev = None
while current and current.data != key:
prev = current
current = current.next

# If the node wasn't found


if current is None:
print("Node not found")
return

# Unlink the node from the list


prev.next = current.next
current = None # Free the node

# 5. Search for a node by value


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

# Example usage of the LinkedList class


ll = LinkedList()

# Add nodes to the linked list


ll.append(10) # Add 10 at the end
ll.append(20) # Add 20 at the end
ll.append(30) # Add 30 at the end

# Display the list


ll.display() # Output: 10 -> 20 -> 30 -> None

# Add node at the beginning


ll.prepend(5) # Add 5 at the beginning

# Display the list again


ll.display() # Output: 5 -> 10 -> 20 -> 30 -> None

# Delete a node
ll.delete(20) # Delete the node with value 20
ll.display() # Output: 5 -> 10 -> 30 -> None

# Search for a node


print(ll.search(10)) # Output: True (since 10 exists)
print(ll.search(100)) # Output: False (since 100 does not exist)

What might cause the error?

1. Code Ordering: The LinkedList class must be defined before you create an instance of
it (ll = LinkedList()), or Python will not recognize it.
o Correct Order: Class definitions come first.
o Incorrect Order: If you try to use LinkedList before it is defined, Python will throw an
error like name 'LinkedList' is not defined.
2. Typo: Ensure there are no typos in the class name (LinkedList). Python is case-
sensitive, so make sure the class name is exactly the same when creating an instance.

Common Fixes

1. Double-check that the LinkedList class is defined before the part where you create an
instance (ll = LinkedList()).
2. Ensure there is no typo in the class name or the reference to it.

explain double linked list with example iin detail viusalize


ChatGPT said:

ChatGPT
Doubly Linked List Explanation

A Doubly Linked List (DLL) is a type of linked list where each node contains three parts:

1. Data: The value stored in the node.


2. Next: A pointer/reference to the next node in the list.
3. Prev: A pointer/reference to the previous node in the list.

In a Doubly Linked List, nodes can be traversed in both directions:

 Forward traversal (from the head to the tail)


 Backward traversal (from the tail to the head)

The head points to the first node, and the tail points to the last node. The next pointer of the last
node is None, and the prev pointer of the first node is also None.

Advantages of Doubly Linked Lists

 Two-way Traversal: You can traverse both forward and backward, unlike singly linked
lists where only forward traversal is possible.
 Efficient Deletion: Deletion of a node can be done more easily, especially if we have a
reference to the node to be deleted, since we can easily access both its previous and next
nodes.
 Bidirectional Traversal: It is possible to navigate from the first node to the last node
(forward) or from the last node to the first node (backward).

Disadvantages

 Extra Space: Each node requires additional space for the prev pointer.
 Complexity: More complex to implement than a singly linked list due to the
management of two pointers per node.

Doubly Linked List Example in Python

1. Define a Node Class

Each node will have three attributes:

 data: The value of the node.


 next: A pointer/reference to the next node.
 prev: A pointer/reference to the previous node.

2. Define the Doubly Linked List Class

The DoublyLinkedList class will handle various operations like insertion, deletion, traversal,
etc.

Full Code Example


python
Copy code
class Node:
def __init__(self, data):
self.data = data # Store data
self.next = None # Pointer to the next node
self.prev = None # Pointer to the previous node

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

# 1. Insert a new node at the beginning (prepend)


def prepend(self, data):
new_node = Node(data)
if self.head is None: # If the list is empty
self.head = self.tail = new_node # The new node is both head and
tail
else:
new_node.next = self.head # The new node's next points to the
current head
self.head.prev = new_node # The current head's prev points to the
new node
self.head = new_node # Update the head to the new node

# 2. Insert a new node at the end (append)


def append(self, data):
new_node = Node(data)
if self.tail is None: # If the list is empty
self.head = self.tail = new_node # The new node is both head and
tail
else:
self.tail.next = new_node # The current tail's next points to the
new node
new_node.prev = self.tail # The new node's prev points to the
current tail
self.tail = new_node # Update the tail to the new node

# 3. Display the entire list (Forward Traversal)


def display(self):
current = self.head
while current:
print(current.data, end=" <-> ")
current = current.next
print("None") # End of the list

# 4. Display the list in reverse order (Backward Traversal)


def display_reverse(self):
current = self.tail
while current:
print(current.data, end=" <-> ")
current = current.prev
print("None") # End of the list

# 5. Delete a node by its value


def delete(self, key):
current = self.head
# Find the node to delete
while current:
if current.data == key:
# If it's the first node
if current.prev is None:
self.head = current.next # Move head to next node
if self.head: # If list is not empty after deletion
self.head.prev = None # Set the new head's prev to
None
# If it's the last node
elif current.next is None:
self.tail = current.prev # Move tail to previous node
self.tail.next = None # Set the new tail's next to None
# If it's a middle node
else:
current.prev.next = current.next # Set the previous
node's next to current node's next
current.next.prev = current.prev # Set the next node's
prev to current node's prev
current = None # Free the node
return
current = current.next
print("Node not found")

# 6. Search for a node by value


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

Operations Explanation

1. prepend(data): Adds a new node at the beginning of the list.


o When the list is empty: Both head and tail are set to the new node.
o When the list is not empty: The new node's next points to the current head, and
the current head's prev points to the new node. Then, the head is updated to the
new node.
2. append(data): Adds a new node at the end of the list.
o When the list is empty: Both head and tail are set to the new node.
o When the list is not empty: The current tail's next points to the new node, and
the new node's prev points to the current tail. Then, the tail is updated to the
new node.
3. display(): Traverses the list from the head to the tail and prints the node data in the
order head -> ... -> tail.
4. display_reverse(): Traverses the list from the tail to the head and prints the node data
in the order tail -> ... -> head.
5. delete(key): Deletes the first occurrence of a node with the specified value (key). It
handles:
o The head node: If the node is the first node, it updates the head.
o The tail node: If the node is the last node, it updates the tail.
o A middle node: If the node is somewhere in the middle, it adjusts the next
pointer of the previous node and the prev pointer of the next node.
6. search(key): Searches for a node with the given value (key) and returns True if found,
otherwise returns False.

Example Usage
python
Copy code
# Create a Doubly Linked List object
dll = DoublyLinkedList()

# Add nodes to the list


dll.append(10)
dll.append(20)
dll.append(30)

# Display the list


dll.display() # Output: 10 <-> 20 <-> 30 <-> None

# Add a node at the beginning


dll.prepend(5)

# Display the list again


dll.display() # Output: 5 <-> 10 <-> 20 <-> 30 <-> None

# Display the list in reverse order


dll.display_reverse() # Output: 30 <-> 20 <-> 10 <-> 5 <-> None

# Delete a node
dll.delete(20)

# Display the list after deletion


dll.display() # Output: 5 <-> 10 <-> 30 <-> None

# Search for a node


print(dll.search(10)) # Output: True (since 10 exists)
print(dll.search(40)) # Output: False (since 40 does not exist)

Visual Representation

Initial State (Empty DLL):

rust
Copy code
head -> None
tail -> None

After dll.append(10):

rust
Copy code
head -> 10 <-> None
tail -> 10

After dll.append(20):

rust
Copy code
head -> 10 <-> 20 <-> None
tail -> 20
After dll.prepend(5):

rust
Copy code
head -> 5 <-> 10 <-> 20 <-> None
tail -> 20

After dll.delete(10):

rust
Copy code
head -> 5 <-> 20 <-> None
tail -> 20

After dll.display_reverse():

rust
Copy code
tail -> 20 <-> 5 <-> None
head -> 5

Summary

 Doubly Linked List (DLL) allows for bidirectional traversal (both forward and
backward).
 Each node contains three parts: data, next, and prev.
 Operations like insertion, deletion, and search are more efficient compared to singly
linked lists due to the extra prev pointer.
 DLL is used when there is a need for bidirectional navigation or efficient deletion from
both ends.

Let me know if you'd like further explanations or have any questions!

4o mini

You might also like