Solving in JS. Reverse a Linked List

Reverse a singly linked list.Example:Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Let create a new Node. Each node are not connected.
let one = new Node(1)
let two = new Node(2)
let three = new Node(3)
let four = new Node(4)
1 2 3 4
The node are connect to another using the next property.
one.next = two
two.next = three
three.next = four
1->2->3->4->null
Version1
Node {
val: 1,
next: Node { val: 2, next: Node { val: 3, next: Node { val: 4, next: null} } }
}
Version2
Node {
val: 1,
next: Node {
val: 2,
next: Node {
val: 3,
next: Node{
val: 4,
next: null
}
}
}
}
H        T
1->2->3->4->null
T H
null<-1<-2<-3<-4
function reverse(head) {
let previousNode = null
while(head !== null){
let nextNode = head.next
head.next = previousNode
previousNode = head
head = nextNode
}
return previousNode
}
  1. We need to first need to create a previous node and set it to null.
  2. We are currently at the head, node 1.
  3. While the head in not null, we can do something with it.
  4. We first need to create a temporary variable call nextNode. Using head.next, we assign nextNode = node 2.
  5. We now need to change the pointer direction, rather having the pointer point to node 2, we want pointer to point to the previousNode which is null.
  6. After changing the direction of .next from we can update the previousNode and the head to move onto the next iteration. Assign previousNode = node 1 and head = node 2.
  7. Remember order matter on how you call your variables.
previousNode = head       previousNode = node 1
head = nextNode head = node 2
head = nextNode head = node 2
previousNode = head previousNode = node 2

--

--

--

Copy and Paste what’s on my mind. Perfect.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Understanding the JavaScript — Basics

Demystifying and Setting up .babelrc

Build a Login System in Node.js

Submit Form with Files using Javascript

How to deal with shadow dom elements when shadow-root is closed with selenium?

Django Rest Framework Simple JWT

How to test React websocket implementation using cypress

Next Greater Element I

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dong Xia

Dong Xia

Copy and Paste what’s on my mind. Perfect.

More from Medium

Deep Dive into Data structures using Javascript — Doubly Linked List

Getters And Setters: What Are Getters And Setters In JavaScript ?

Image of numbers on a dice

Dynamic Programming Tutorial using JavaScript

The Replacements JavaScript Algorithm