Skip to content

Commit a8166cf

Browse files
authored
Create LinkedList-Bubble Sort (Iterative) LinkedList
1 parent 97af100 commit a8166cf

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
Given a singly linked list of integers, sort it using 'Bubble Sort.'
2+
Note :
3+
No need to print the list, it has already been taken care. Only return the new head to the list.
4+
Input format :
5+
The first and the only line of each test case or query contains the elements of the singly linked list separated by a single space.
6+
Remember/Consider :
7+
While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element
8+
Output format :
9+
For each test case/query, print the elements of the sorted singly linked list.
10+
11+
Output for every test case will be printed in a seperate line.
12+
Constraints :
13+
0 <= M <= 10^3
14+
Where M is the size of the singly linked list.
15+
16+
Time Limit: 1sec
17+
Sample Input 1 :
18+
10 9 8 7 6 5 4 3 -1
19+
Sample Output 1 :
20+
3 4 5 6 7 8 9 10
21+
Sample Input 2 :
22+
10 -5 9 90 5 67 1 89 -1
23+
Sample Output 2 :
24+
-5 1 5 9 10 67 89 90
25+
26+
*******************************************Code*******************************************
27+
public static LinkedListNode<Integer> bubbleSort(LinkedListNode<Integer> head) {
28+
29+
if(head==null || head.next==null)
30+
return head;
31+
for(int i=0;i<lengthLL(head)-1;i++)
32+
{
33+
LinkedListNode<Integer> prev=null;
34+
LinkedListNode<Integer> cur=head;
35+
LinkedListNode<Integer>next=cur.next;
36+
while(cur.next!=null)
37+
{
38+
if(cur.data>cur.next.data)
39+
{
40+
if(prev==null)
41+
{
42+
cur.next=next.next;
43+
next.next=cur;
44+
prev=next;
45+
head=prev;
46+
}
47+
else
48+
{
49+
next=cur.next;
50+
cur.next=next.next;
51+
prev.next=next;
52+
next.next=cur;
53+
prev=next;
54+
}
55+
}
56+
else{
57+
prev=cur;
58+
cur=cur.next;
59+
}
60+
}
61+
}
62+
return head;
63+
}
64+
private static int lengthLL(LinkedListNode<Integer> head)
65+
{
66+
int cnt=1;
67+
while(head.next!=null)
68+
{
69+
head=head.next;
70+
cnt++;
71+
}
72+
return cnt;
73+
}
74+
75+

0 commit comments

Comments
 (0)