Untitled
unknown
plain_text
a year ago
1.2 kB
8
Indexable
public class Solution {
public ListNode sortLinkedList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode zeroTail = new ListNode(0);
ListNode oneTail = new ListNode(0);
ListNode twoTail = new ListNode(0);
ListNode zeroHead = zeroTail, oneHead = oneTail, twoHead = twoTail;
// Partition the list into three separate lists
ListNode current = head;
while (current != null) {
if (current.val == 0) {
zeroTail.next = current;
zeroTail = zeroTail.next;
} else if (current.val == 1) {
oneTail.next = current;
oneTail = oneTail.next;
} else {
twoTail.next = current;
twoTail = twoTail.next;
}
current = current.next;
}
// Connect the three lists
zeroTail.next = (oneHead.next != null) ? oneHead.next : twoHead.next;
oneTail.next = twoHead.next;
twoTail.next = null;
return zeroHead.next;
}
}
Editor is loading...
Leave a Comment