How to Solve All Linked-List Problems with Relative Ease

A Foolproof Strategy to Solving Linked List Questions:

Learning how to manipulate Linked Lists using their built in methods is an important skill, however if you are at an interview and are unable to figure out the complicated logic, or are doing competitive programming and are pressed for time, a foolproof strategy is to first convert the problem to a List problem, solve the trivial list solution and then convert the list back to a Linked List. This will usually run a bit slower than without any conversions, however the solution remains of order O(N) which is typically optimal for LinkedList questions. The benefit is that you save yourself from the complicated task of conjuring completely bug-free code while under time pressure, and in my opinion a working, suboptimal solution is better than no solution at all.

The strategy is as follows:

1. Convert the linked list to a regular list:

nodeList = []
while head:
	nodeList.append(head.val)
	head = head.next

2. Perform the required List operations
328 Odd Even Linked List : nodeList = nodeList[::2]+nodeList[1::2]
148 Sort List: nodeList.sort()
206 Reverse Linked List: nodeList = nodeList[::-1]
... and so on, and so forth ...

3. Convert back to a Linked List

	newHead = temp = ListNode()
	for i in nodeList:
		temp.next = ListNode(i)
		temp = temp.next
	return newHead.next
Comments (3)