-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinked List 2:Bubble Sort (Iterative) LinkedList
45 lines (40 loc) · 1.29 KB
/
Linked List 2:Bubble Sort (Iterative) LinkedList
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class Solution {
public static LinkedListNode<Integer> bubbleSort(LinkedListNode<Integer> head )
{ if(head==null || head.next==null)
return head;
//Write your code here
for(int i=0;i<lengthLL(head)-1;i++){
LinkedListNode<Integer> prev = null;
LinkedListNode<Integer> curr = head;
LinkedListNode<Integer> next = curr.next;
while(curr.next != null){
if(curr.data > curr.next.data){
if(prev == null){
curr.next = next.next;
next.next = curr;
prev = next;
head = prev;
}else{
next = curr.next;
curr.next = next.next;
prev.next = next;
next.next = curr;
prev = next;
}
}else{
prev = curr;
curr = curr.next;
}
}
}
return head;
}
private static int lengthLL(LinkedListNode<Integer> head){
int count = 1;
while(head.next != null){
head = head.next;
count++;
}
return count;
}
}