I realize this sort of data structure is better done with built in list type, but I’m trying to understand this more for academic reasons. Given that I have a linked list like this:
a -> b -> c -> d -> e -> f
I would like to change the references to
b -> a -> d -> c -> f -> e
In other words every pair gets switched. I am using these two classes to create a linked list.
class Node:
def __init__(self):
self.cargo = None
self.next = None
class LinkedList:
def __init__(self):
self.cur_node = None
def add_node(self, cargo):
new_node = Node()
new_node.cargo = cargo
new_node.next = self.cur_node
self.cur_node = new_node
def print_list(self):
node = self.cur_node
while node:
print node.cargo
node = node.next
def reorder(self):
# missing code here!
ll = LinkedList()
ll.add_node("a")
ll.add_node("b")
ll.add_node("c")
ll.add_node("d")
ll.add_node("e")
ll.add_node("f")
ll.reorder()
ll.print_list()
Any ideas?
Sometimes the best thing is to first think “how fast would an optimal solution be?” This seems pretty apparently O(length), so something that runs through the list, preferably once, is going to be about as good as you can do.
Given that, you’re probably going to find the simplest choice is best. In pseudocode, it would be
As Matt and Jodaka note, you do need to decide what to do with an odd-length list, if an odd-length list is permitted at all.