class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public class BubbleSortLinkedList {
Node head;
public void insert(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
public void bubbleSort() {
if (head == null || head.next == null) {
return;
}
boolean swapped;
do {
swapped = false;
Node current = head;
Node prev = null;
while (current.next != null) {
if (current.data > current.next.data) {
Node temp = current.next;
current.next = temp.next;
temp.next = current;
if (prev == null) {
head = temp;
} else {
prev.next = temp;
}
prev = temp;
swapped = true;
} else {
prev = current;
current = current.next;
}
}
} while (swapped);
}
public void display() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public static void main(String[] args) {
BubbleSortLinkedList list = new BubbleSortLinkedList();
list.insert(34);
list.insert(10);
list.insert(64);
list.insert(51);
list.insert(32);
list.insert(21);
System.out.println("Original linked list:");
list.display();
list.bubbleSort();
System.out.println("Linked list after Bubble Sort:");
list.display();
}
}