Move Last Node to Front of Linear Linked List

What’s up everyone?!  I hope everyone’s been doing well as always. Today I am going to work on another linear linked list problem.

The prompt is: Write a function to move the last node to the front of a linear linked list. You could do this iteratively or recursively, I’m just going to go with iteratively for this one.

    # move last to front
    def moveLastToFront(self):

        current = self.head
        previous = None
        temp = None

        # empty or single node
        if not current or not current.next:
            return

        # traverse the list
        while current is not None and current.next is not None:
            temp = current
            previous = current
            current = current.next

        previous.next = None

        # you could write your own push function here
        self.addBeginning(temp.data)

Of course there are much more efficient ways of writing this. I would say the trick is how to keep track of the last node and the node before last, that way you do not lose the data that you’re trying to move. If you have questions, feel free to post in the comments below!