# LeetCode – Sort List (Java)

LeetCode - Sort List:

Sort a linked list in O(n log n) time using constant space complexity.

Analysis

If this problem does not have the constant space limitation, we can easily sort using a sorting method from Java SDK. With the constant space limitation, we need to do some pointer manipulation.

1. Break the list to two in the middle
2. Recursively sort the two sub lists
3. Merge the two sub lists

Java Solution

When I revisit this problem in 2018, I wrote it the following way which is more concise.

Category >> Algorithms
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code>
String foo = "bar";
</code></pre>
• Saikiran Narlapuram
• Arnaud Hebert

Works fine if you change int count = 0; with int count = 1;

• henrycan1414

it is the same since p1.val == p2. val

• Neel Sheyal

If the list is empty or only one element in it, then return the list.
Divide the linked list into two parts.
Sort these two parts recursively.
Merge the sorted parts.

• Frank

This line
pNew.next.next = new ListNode(p1.val);

Should be

pNew.next.next = new ListNode(p2.val);

• anchao1987

• tia

A little bit change to merge function works. Create extra nodes is unnecessary

public ListNode merge(ListNode l, ListNode r){

ListNode lp = l, rp = r;

while(lp!=null || rp!=null){

if(lp==null){

cur.next = rp;

break;

}else if(rp==null){

cur.next = lp;

break;

}else{

if(lp.val <= rp.val){

cur.next = lp;

lp = lp.next;

cur = cur.next;

}else {

cur.next = rp;

rp = rp.next;

cur = cur.next;

}

}

}

}

• Raghav

I’m getting stack overflow error for size of length greater than 3.

• Lister

Definitely not correct. You are creating new nodes.

• Wei Qiu

It’s not correct if you consider the space used by call stack.