Sorting a singly linked list using the bubble sort algorithm involves repeatedly traversing the list and swapping adjacent elements if they are in the wrong order. Here's an example of how you can implement bubble sort for a singly linked list in a hypothetical programming language:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
def bubble_sort_linked_list(head):
if head is None:
return None
# Flag to check if any swaps were made in the pass
swapped = True
while swapped:
swapped = False
current = head
prev = None
while current and current.next:
if current.data > current.next.data:
# Swap the nodes
if prev is not None:
prev.next = current.next
else:
head = current.next
current.next, current.next.next = current.next.next, current
prev = current.next
swapped = True
else:
prev = current
current = current.next
return head
def print_linked_list(head):
current = head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
# Example usage:
if __name__ == "__main__":
# Create a sample linked list
a = Node(5)
b = Node(3)
c = Node(8)
d = Node(1)
e = Node(6)
a.next = b
b.next = c
c.next = d
d.next = e
print("Original linked list:")
print_linked_list(a)
sorted_list = bubble_sort_linked_list(a)
print("Linked list after bubble sort:")
print_linked_list(sorted_list)
```
This code defines a `Node` class for the linked list elements and implements the `bubble_sort_linked_list` function to sort the linked list in ascending order. The `print_linked_list` function is used to print the linked list before and after sorting. You can adapt this code to your programming language of choice while keeping the logic intact.