0s & 1s Linked List
unknown
java
a year ago
790 B
6
Indexable
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
class Solution {
public ListNode sortBinaryList(ListNode head) {
int zeroCount = 0, oneCount = 0;
ListNode temp = head;
// Count number of 0s and 1s
while (temp != null) {
if (temp.val == 0) zeroCount++;
else oneCount++;
temp = temp.next;
}
// Modify the linked list based on counts
temp = head;
while (zeroCount-- > 0) {
temp.val = 0;
temp = temp.next;
}
while (oneCount-- > 0) {
temp.val = 1;
temp = temp.next;
}
return head;
}
}
Editor is loading...
Leave a Comment