I wrote my first program back in 1984 on Sinclair ZX Spectrum, and have been in the software industry as a professional since 1994. Besides being an active member of the industry, I'm also a university professor using LeetCode for many inspirational examples. What I've frequently noticed, like in the case of the Sort List problem, crucial perspectives, important for you as a future member of big corporations, are neglected. One of these aspects is reuse based software engineering.
The official solution for the Sort List problem only focuses on reimplementing everything from scratch, which is rarely the best approach in software corporations. You must also think in terms of reusing available stuff, for example, those offered as part of the standard library in your programming environment. I will use Java, but the story applies to other languages, too. One way to solve the previously mentioned task is to leverage the Adapter design pattern and simply call the standard Collections.sort method. For the sake of completeness, below is one possible solution. Of course, there are many other approaches, but the key takeaway is to consider reuse, too.
import java.util.AbstractSequentialList;
class Solution {
// Applies the Adapter design pattern for the custom linked list.
private static class ListNodeAdapter extends AbstractSequentialList<Integer> {
private final ListNode head;
private final int size;
private ListNode tail;
ListNodeAdapter(ListNode head) {
this.head = head;
size = fastForward(Integer.MAX_VALUE);
}
private int fastForward(int limit) {
var count = 0;
tail = head;
while (count < limit && tail != null) {
tail = tail.next;
count++;
}
return count;
}
@Override
public ListIterator<Integer> listIterator(int index) {
return new ListIterator<Integer>() {
private ListNode curr;
private ListNode prev;
private int i;
{
fastForward(index);
curr = tail;
assert curr != null;
}
@Override
public boolean hasNext() { return curr != null; }
@Override
public Integer next() {
prev = curr;
curr = curr.next;
i++;
return prev.val;
}
@Override
public int nextIndex() { return i; }
@Override
public void set(Integer val) { prev.val = val; }
@Override
public boolean hasPrevious() { return false; }
@Override
public Integer previous() { throw new UnsupportedOperationException(); }
@Override
public int previousIndex() { throw new UnsupportedOperationException(); }
@Override
public void remove() { throw new UnsupportedOperationException(); }
@Override
public void add(Integer val) { throw new UnsupportedOperationException(); }
};
}
@Override
public int size() { return size; }
}
public ListNode sortList(ListNode head) {
if (head != null) Collections.sort(new ListNodeAdapter(head));
return head;
}
}Observe that the sortList method is trivial. Furthermore, the ListNodeAdapter is nothing else than a straightforward scaffolding whose implementation is a no-brainer. If you provide such solutions to your employer, then you will be surely heralded as a productive team member.