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)
100000
-1000000000
and 1000000000
O(n)
O(1)
You can see the full challenge with visuals at this link.
Challenges • Asked almost 7 years ago by Jake from AlgoDaily
This is the main discussion thread generated for Reverse a Linked List.