Community

Start a Thread


Notifications
Subscribe You’re not receiving notifications from this thread.

Reverse a Linked List (Main Thread)

Here is the interview question prompt, presented for reference.

You're sent a linked list of numbers, but it's been received in the opposite order to what you need. This has happened multiple times now, so you decide to write an algorithm to reverse the lists as they come in. The list you've received is as follows:

7 -> 2 -> 21 -> 6 -> 42 -> 10

Write an algorithm for a method reverseList that takes in a head node as a parameter, and reverses the linked list. It should be capable of reversing a list of any length.

You may use the example linked list for testing purposes. Your method will be called as such:

class LinkedListNode {
  constructor(val, next = null) {
    this.val = val;
    this.next = next;
  }
}

l1 = new LinkedListNode(1);
l1.next = new LinkedListNode(2);
reverseList(l1);
class Node:
    def __init__(self, val):
        self.val = val
        self.next = None

l1 = Node(1)
l1.next = Node(2)
reverse_list(l1)

Constraints

  • Length of the given LinkedList <= 100000
  • The nodes will always contain integer values between -1000000000 and 1000000000
  • Expected time complexity : O(n)
  • Expected space complexity : O(1)

You can see the full challenge with visuals at this link.

Challenges • Asked over 6 years ago by Jake from AlgoDaily

Jake from AlgoDaily Commented on Nov 30, 2017:

This is the main discussion thread generated for Reverse a Linked List.