LeetCode Notes: Reverse Linked List

Question

Define a function, input the head node of a linked list, reverse the linked list and output the head node of the reversed linked list.

Example:

Input: 1->2->3->4->5->NULL

Output: 5->4->3->2->1->NULL

limit:

0 <= number of nodes <= 5000

Solution

Analysis:

Look up the entire linked list in a loop, each time a new parent node is created to point to the current node, and the last generated parent node is the head node after inversion

Code:

/**
  * Definition for singly-linked list.
  * function ListNode(val) {
  * this.val = val;
  * this.next = null;
  *}
  */
/**
  * @param {ListNode} head
  * @return {ListNode}
  */
var reverseList = function(head) {
     let next = null
     // loop to the end of the linked list
     while(head != null){
        
         // Generate a parent node with byte points
         const node = {
             val:head.val,
             next:next
         }
        
         // move to the next position
         head = head.next
         next = node

     }
    
     return next
};

Test:

//Define a 1->2->3->4->5 linked list
var list = {
     val:1,
     next:{
         val:2,
         next:{
             val:3,
             next:{
                 val:4,
                 next:{
                     val:5,
                     next:null

                 }

             }

         }
     }
}
//Reverse linked list
reverseList(list) //Output: 5->4->3->2->1

Reference

Comments