Bubble Sort for Linked List by Swapping nodes
Given a singly linked list, sort it using bubble sort by swapping nodes.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: 10->30->20->5 Output: 5->10->20->30 Input: 20->4->3 Output: 3->4->20
- Get the Linked List to be sorted
- Apply Bubble Sort to this linked list, in which, while comparing the two adjacent nodes, actual nodes are swapped instead of just swapping the data.
- Print the sorted list
Below is the implementation of the above approach:
Linked list before sorting 5 -> 1 -> 32 -> 10 -> 20 -> 78 -> Linked list after sorting 1 -> 5 -> 10 -> 20 -> 32 -> 78 ->