Given a linked list of integers, split it into two lists containing alternating elements from the original list.

For example, if the original list is {1, 2, 3, 4, 5}, then one sublist should be {1, 3, 5} and the other should be {2, 4}. The elements in the output lists may be in any order. i.e., the sublists can be {5, 3, 1} and {4, 2} for input list {1, 2, 3, 4, 5}.

Practice this problem

1. Using moveNode() function

The simplest approach iterates over the source list and use moveNode() to pull nodes off the source and alternately put them on a and b. The only strange part is that the nodes will be in the reverse order in the source list.

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

C


Download  Run Code

Output:

First List: 7 —> 5 —> 3 —> 1 —> NULL
Second List: 6 —> 4 —> 2 —> NULL

Java


Download  Run Code

Output:

First List: 7 —> 5 —> 3 —> 1 —> null
Second List: 6 —> 4 —> 2 —> null

Python


Download  Run Code

Output:

First List: 7 —> 5 —> 3 —> 1 —> None
Second List: 6 —> 4 —> 2 —> None

2. Using Dummy Nodes

Here is an alternative approach that builds the sublists in the same order as the source list. The code uses temporary dummy header nodes for the a and b lists as they are being built. Each sublist has a “tail” pointer that points to its current last node – that way, new nodes can be appended at the end of each list easily. The dummy nodes give the tail pointers something to point to initially. The dummy nodes are efficient in this case because they are temporary and allocated in the stack.

Following is the C, Java, and Python implementation of the idea:

C


Download  Run Code

Output:

First List: 1 —> 3 —> 5 —> 7 —> NULL
Second List: 2 —> 4 —> 6 —> NULL

Java


Download  Run Code

Output:

First List: 1 —> 3 —> 5 —> 7 —> null
Second List: 2 —> 4 —> 6 —> null

Python


Download  Run Code

Output:

First List: 1 —> 3 —> 5 —> 7 —> None
Second List: 2 —> 4 —> 6 —> None

3. Using Recursion

We can easily solve this problem by recursion as well. The recursive implementation can be seen below in C, Java, and Python:

C


Download  Run Code

Output:

First List: 1 —> 3 —> 5 —> 7 —> NULL
Second List: 2 —> 4 —> 6 —> NULL

Java


Download  Run Code

Output:

First List: 1 —> 3 —> 5 —> 7 —> null
Second List: 2 —> 4 —> 6 —> null

Python


Download  Run Code

Output:

First List: 1 —> 3 —> 5 —> 7 —> None
Second List: 2 —> 4 —> 6 —> None

The time complexity of both above-discussed methods is O(n), where n is the length of the linked list. The iterative version doesn’t require any extra space, whereas the recursive version use stack space proportional to the lists’ length.

 
Exercise: Modify the solution to use “local references” technique to get rid of the dummy nodes.

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