JavaScript Challenge - Reverse a Singly-Linked List

This community-built FAQ covers the “Reverse a Singly-Linked List” code challenge in JavaScript. You can find that challenge here, or pick any challenge you like from our list.

Top Discussions on the JavaScript challenge Reverse a Singly-Linked List

There are currently no frequently asked questions or top answers associated with this challenge – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this challenge. Ask a question or post a solution by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this challenge, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

Looking for motivation to keep learning? Join our wider discussions in #community

Learn more about how to use this guide.

Found a bug? Report it online, or post in #community:Codecademy-Bug-Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Hello everyone, :smiley:

I resolved that challenge and want to share my answer with you :

function reverseLinkedList(linkedList) {
//linkedList argument represents the head of the Linked List

let prevPointer = null
let currentPointer = linkedList
let nextPointer = null

while (currentPointer !== null) {

//the pointer that should come after the current pointer now comes before the current pointer
prevPointer = currentPointer.next
//the first pointer will be the last so the next pointer of the current pointer should be null for the first iteration
currentPointer.next = nextPointer
//the pointer that will be the next pointer must be the current pointer
nextPointer = currentPointer
//the current pointer should now be the previous pointer of the initial current pointer
currentPointer = prevPointer

}
return nextPointer
}

Enjoy coding everyone ! :jigsaw: :wink:

4 Likes

I was a bit lazy and just put all the nodes in the list into an array,
and then used the indices in the array to switch the .next

function reverseLinkedList(linkedList) {
  let nodeList = [];
  let current = linkedList;
  while(current) {
    nodeList.push(current);
    current = current.next;
  }
  const lastIndex = nodeList.length - 1;
  for (let i = 0; i < lastIndex; i++) {
    nodeList[i + 1].next = nodeList[i];
  }
  if (lastIndex >= 0) {
    nodeList[0].next = null;
    return nodeList[lastIndex];
  }
}

Hey guys,

I proudly present my code solution to the reverse linked list challenge.


function reverseLinkedList(linkedList){

let currentNode = linkedList;
let previousNode = null;
let newNode = null;

while(currentNode !== null) {
  newNode = new Node(currentNode.data)
  newNode.next = previousNode;
  previousNode = newNode;
  currentNode = currentNode.next;
}

return newNode;
}

I appear to have been ever lazier :sweat_smile:


function reverseLinkedList(linkedList){
  const listArray = [];
  let current = linkedList;

  while (current) {
    listArray.push(current.data);
    current = current.next;
  }
  listArray.reverse()

  return makeLinkedList(listArray);

}

1 Like

Finally solved it, using the first function.
Had to look it up, not being able to fix it at first.
First i wrote the second function, that worked but didn’t pass.
Tried to keep the runtime shorter by implementing edge cases.
Do you think the edge cases are helping? Or neglectable?

Such a simple elegant solution, for what seems like a difficult problem;
PS: the code below will throw an error, based on the missing imports

const makeLinkedList = require('./makeLinkedList.js'); // O(n) time & O(1) space function reverseLinkedList(head){ let prev = null; let next = null; // we are going to reverse the arrows /pointers //the first node will become the last, and will therefore point to null // we will do this by storing the head's pointer first in a a varibale.pointing it to the previous node'. //first we have to store the head's next node in a a variable, to save it for the next iteration while (head !== null){ //first we have to store the head's next node in a a variable, to save it for the next iteration next = head.next; //then we reset the head nodes pointer to the previous node. in the first iteration, this will be null head.next = prev; //now, we set the prev variable to the head, for the next iteration. This is so in the next iteration, the head.next can be set to the previous node. prev = head; //now we continue the iteration cycle, by changing the head variable to the previously stored next node: the next node in the original list for processing. head = next; } //when head > the last node of the list, the loop breaks. we now return prev, since that it is the last processed node of the iteration cycle, therfore making it the new head return prev; } function reverseLinkedListX(linkedList){ // Write your code here let prev = null; let head = linkedList; let next = null; //check if the list has two or more items if (head.next === null){ console.log('Only one item in the list, no need to reverse!'); return head; } //continue if it has more than one item next = head.next; //if it only has two items if (next.next === null){ next.next = head; head.next = prev; return next; } else { // has more then two items while (head !== null){ next = head.next; head.next = prev; prev = head head = next; } return prev; } } //Calling your function on an example console.log("Original") let exampleLinkedList = makeLinkedList([3,2,1]); exampleLinkedList.print() console.log("Reversed") let reversed = reverseLinkedList(exampleLinkedList); reversed.print() // Leave this here so we can test your code module.exports = reverseLinkedList;

Great turn of mind, )

function reverseLinkedList(linkedList){
  // Write your code here
  let node = linkedList;
  let newHead = null;

  while(node != null){

    let newNode = {data:node.data, next:null};
    newNode.next = newHead;
    newHead = newNode;
    node = node.next;

  }
  return newHead;
}

Here’s my code for this challenge. I use two pointers to reverse the direction of each link in O(n) time and return the end (new head) node.

const Node = require('./Node.js'); const makeLinkedList = require('./makeLinkedList.js'); function reverseLinkedList(linkedList){ if (!linkedList) { return linkedList } // Write your code here let x = linkedList let y = linkedList.next x.next = null while (y) { const temp = y.next // Reverse direction y.next = x x = y y = temp } return x } //Calling your function on an example console.log("Original") let exampleLinkedList = makeLinkedList([1, 2, 3]) exampleLinkedList.print() console.log("Reversed") let reversed = reverseLinkedList(exampleLinkedList) reversed.print() // Leave this here so we can test your code module.exports = reverseLinkedList;

Hello,this my solution))

Preformatted textconst Node = require(‘./Node.js’);
const makeLinkedList = require(‘./makeLinkedList.js’);

function reverseLinkedList(linkedList){
let prev =null
let current = linkedList

while(current){
const next = current.next
current.next = prev
prev = current
current = next
}
// Write your code here
return prev
}

//Calling your function on an example
console.log(“Original”)
let exampleLinkedList = makeLinkedList([4, 8, 15])
exampleLinkedList.print()
console.log(“Reversed”)
let reversed = reverseLinkedList(exampleLinkedList)
reversed.print()
// Leave this here so we can test your code
module.exports = reverseLinkedList;

I got roughly the same answer as everyone else. I used 3 pointers: variables for previous, current, and next node.

Summary
const Node = require('./Node.js');
const makeLinkedList = require('./makeLinkedList.js');

function reverseLinkedList(linkedList){
  if (linkedList == null) {
    return linkedList;
  }
  let originalHead = linkedList;
  let previous = null;
  let current = originalHead;
  let next = current.next;
  while(next) {
    next = current.next;
    current.next = previous;
    previous = current;
    current = next;
  }
  const newHead = previous || originalHead;
  return newHead;
}
class Node { constructor(value = null) { this.value = value; this.next = null; }; print() { let current = this; let output = "" + current.value; while (current.next) { current = current.next; output += " -> " + current.value; } output += " -> None"; console.log(output); //return output; } } function makeLinkedList(array) { let head = null; let current; let previous = null; for (let element of array) { current = new Node(element); if (previous) { previous.next = current; } else { head = current; } previous = current; } return head; } function reverseLinkedList(linkedList){ if (linkedList == null) { return linkedList; } let originalHead = linkedList; let previous = null; let current = originalHead; let next = current.next; while(next) { next = current.next; current.next = previous; previous = current; current = next; } const newHead = previous || originalHead; return newHead; } //Calling your function on an example console.log("Original"); let exampleLinkedList = makeLinkedList([4, 8, 15]) exampleLinkedList.print(); console.log("Reversed"); let reversed = reverseLinkedList(exampleLinkedList); reversed.print();

Hello evrybody. it is my solution :slight_smile:
const Node = require(‘./Node.js’);
const makeLinkedList = require(‘./makeLinkedList.js’);

function reverseLinkedList(linkedList){
// Write your code here
if (linkedList === null || linkedList.next === null) {
return linkedList;
}
let reversedHead = reverseLinkedList(linkedList.next);
linkedList.next.next = linkedList;
linkedList.next = null;
return reversedHead;
}

//Calling your function on an example
console.log(“Original”)
let exampleLinkedList = makeLinkedList([4, 8, 15])
exampleLinkedList.print()
console.log(“Reversed”)
let reversed = reverseLinkedList(exampleLinkedList)
reversed.print()
// Leave this here so we can test your code
module.exports = reverseLinkedList;

1 Like

I kindda like your recursive solution :wink:

Here is my solution

function reverseLinkedList(head){
  let prev = null
  let next = null

  while ( head ) {
    next = head.next  // Save next Node
    head.next = prev  // Assign previous Node as Next Node
    if ( !next ) { break }  // Break if no next Node
    prev = head  // Current head becomes previous Node
    head = next  // Next Node becomes current head
  }

  return head
}

At first, I came up whit this extremely and unnecessarily complex solution:

function reverseLinkedList(linkedList){
   function findNthNode(linkedList, n) {
    let count = 0;
    let tail = linkedList;
    let current = null;

    while(tail) {
      tail = tail.next;
      if(count >= n) {
        if(!current) {
          current = linkedList;
        }
        current = current.next;
      }
      count++;      
    }

    if(!current && count === n) {
      return linkedList;
    }

    return current;
  }

  let secondToLast = findNthNode(linkedList, 2);
  let tail = findNthNode(linkedList, 1);
  let current = linkedList;

  linkedList = tail;

  while(secondToLast) {
    tail.next = secondToLast;
    secondToLast.next = null;
    secondToLast = findNthNode(current, 2);
    tail = findNthNode(current, 1);
  }

  return linkedList;
}

Also, this solution is not at all time-performant, being O(N²).

Then, I cheated a little bit :grin: since I read it could be solved with O(N) time complexity, and searched for tips on how to achieve this, ending up with this solution (very similar to what others have already posted here):

function reverseLinkedList(linkedList) {
  let previousPointer = null;
  let currentPointer = linkedList;

  while(currentPointer) {
    const nextPointer = currentPointer.next;
    currentPointer.next = previousPointer;
    previousPointer = currentPointer;
    currentPointer = nextPointer;
  }

  return previousPointer;
}