Exercise 1:
Implement a method in the `LinkedList` class that counts the number of occurrences of a target value in
the linked list. The method should return the count of occurrences.
Correction:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# ... Other methods (append, remove, display) ...
def count_occurrences(self, target):
count = 0
current = self.head
while current is not None:
if current.data == target:
count += 1
current = current.next
return count
# Example of calling the method
L = LinkedList()
# Append nodes
L.append(10)
L.append(20)
L.append(30)
L.append(20)
L.append(40)
L.append(20)
# Display the linked list
L.display() # Output: 10 20 30 20 40 20
# Count the occurrences of a target
occurrences = L.count_occurrences(20)
print("Occurrences of 20:", occurrences) # Output: Occurrences of 20: 3
```
In this exercise, we added the `count_occurrences` method to the `LinkedList` class. This method takes a
`target` parameter and counts the number of occurrences of the target value in the linked list.
The method initializes a `count` variable to 0 and starts traversing the list from the head. For each node,
if the node's data matches the target, it increments the count. Finally, the method returns the count of
occurrences.
In the example code, we create a `LinkedList` object `L` and append several nodes with different data
values. We then call the `display` method to print the contents of the linked list.
Afterward, we call the `count_occurrences` method to count the number of occurrences of the target
value 20 in the linked list. The result is stored in the `occurrences` variable and printed.
The output will be:
```
10 20 30 20 40 20
Occurrences of 20: 3
```
This exercise demonstrates how to implement a method in the `LinkedList` class that counts the
occurrences of a target value in the linked list.
Exercise 2:
Implement a method in the `LinkedList` class that reverses the order of the nodes
in the linked list. The method should modify the existing list in-place, without
creating a new list.
Correction:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# ... Other methods (append, remove, display) ...
def reverse(self):
previous = None
current = self.head
while current is not None:
next_node = current.next
current.next = previous
previous = current
current = next_node
self.head = previous
# Example of calling the method
L = LinkedList()
# Append nodes
L.append(10)
L.append(20)
L.append(30)
L.append(40)
L.append(50)
# Display the linked list
L.display() # Output: 10 20 30 40 50
# Reverse the linked list
L.reverse()
# Display the reversed linked list
L.display() # Output: 50 40 30 20 10
```
In this exercise, we added the `reverse` method to the `LinkedList` class. This
method reverses the order of the nodes in the linked list in-place.
The method uses three pointers: `previous`, `current`, and `next_node`. It starts
with `previous` and `current` both pointing to `None` and `self.head` pointing to
the first node of the list.
The method then iterates through the list, updating the `next` reference of the
current node to point to the previous node. After that, it advances `previous`,
`current`, and `next_node` accordingly.
Finally, the method updates the `head` reference of the list to point to the last
node (which is now the first node after the reversal).
In the example code, we create a `LinkedList` object `L` and append several nodes
with different data values. We then call the `display` method to print the initial
contents of the linked list.
Afterward, we call the `reverse` method to reverse the order of the nodes in the
linked list. Finally, we call the `display` method again to print the reversed
contents of the linked list.
The output will be:
```
10 20 30 40 50
50 40 30 20 10
```
This exercise demonstrates how to implement a method in the `LinkedList` class
that reverses the order of the nodes in the linked list in-place.
4
Exercise:
Certainly! Here's another exercise for you:
Implement a method in the `LinkedList` class that checks whether the linked list contains a cycle. A cycle
occurs when a node in the list points to a previous node, creating a loop.
Here's an example implementation of the `has_cycle` method:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# ... Other methods (append, remove, display) ...
def has_cycle(self):
slow = self.head
fast = self.head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
# Example of calling the method
L = LinkedList()
# Append nodes
L.append(10)
L.append(20)
L.append(30)
L.append(40)
# Display the linked list
L.display() # Output: 10 20 30 40
# Check if the linked list has a cycle
has_cycle = L.has_cycle()
print("Has cycle:", has_cycle) # Output: Has cycle: False
# Create a cycle in the linked list
L.head.next.next.next.next = L.head.next
# Check again if the linked list has a cycle
has_cycle = L.has_cycle()
print("Has cycle:", has_cycle) # Output: Has cycle: True
```
In this exercise, we added the `has_cycle` method to the `LinkedList` class. This method uses the "Floyd's
Tortoise and Hare" algorithm to detect if there is a cycle in the linked list.
The method initializes two pointers, `slow` and `fast`, to the head of the list. The `slow` pointer moves
one step at a time, while the `fast` pointer moves two steps at a time. If there is a cycle, the `fast` pointer
will eventually catch up to the `slow` pointer.
The method continues the traversal until either the `fast` pointer reaches the end of the list (indicating
no cycle) or the `slow` and `fast` pointers meet (indicating a cycle).
In the example code, we create a `LinkedList` object `L` and append several nodes with different data
values. We then call the `display` method to print the contents of the linked list.
Afterward, we call the `has_cycle` method to check if the linked list has a cycle. The initial list does not
have a cycle, so the result is `False`.
To create a cycle in the linked list, we make the last node point back to the second node. We then call the
`has_cycle` method again to check if the linked list has a cycle. This time, the result is `True`.
The output will be:
```
10 20 30 40
Has cycle: False
Has cycle: True
```
This exercise demonstrates how to implement a method in the `LinkedList` class that checks whether the
linked list contains a cycle using the "Floyd's Tortoise and Hare" algorithm.