Given a linked list, split it into two sublists – one for the front half and one for the back half. If the total number of elements in the list is odd, the extra element should go in the front list.

For example, list {2, 3, 5, 7, 11} should yield the two lists {2, 3, 5} and {7, 11}.

Practice this problem

1. Naive Solution

Probably the simplest strategy is to compute the length of the list, then use a for loop to hop over the right number of nodes to find the last node of the front half, and then cut the list at that point.

Following is the C, Java, and Python program that demonstrates it:

C


Download  Run Code

Output:

Front List: 6 —> 3 —> 4 —> NULL
Back List: 8 —> 2 —> 9 —> NULL

Java


Download  Run Code

Output:

Front List: 6 —> 3 —> 4 —> null
Back List: 8 —> 2 —> 9 —> null

Python


Download  Run Code

Output:

Front List: 6 —> 3 —> 4 —> None
Back List: 8 —> 2 —> 9 —> None

2. Fast/Slow Pointer Strategy

There is a tricky technique that uses two pointers to traverse the list. A “slow” pointer advances one node simultaneously, while the “fast” pointer goes two nodes at a time. When the fast pointer reaches the end, the slow pointer will be about halfway. For either strategy, care is required to split the list at the right point.

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

Front List: 6 —> 3 —> 4 —> NULL
Back List: 8 —> 2 —> 9 —> NULL

Java


Download  Run Code

Output:

Front List: 6 —> 3 —> 4 —> null
Back List: 8 —> 2 —> 9 —> null

Python


Download  Run Code

Output:

Front List: 6 —> 3 —> 4 —> None
Back List: 8 —> 2 —> 9 —> None

The time complexity of the above solution is O(n), where n is the total number of nodes in the linked list, and doesn’t require any extra space.

 
Source: http://cslibrary.stanford.edu/105/LinkedListProblems.pdf