Q:

reverse a linked list javascript

// O(n) time & O(n) space
function reverse(head) {
  if (!head || !head.next) {
    return head;
  }
  let tmp = reverse(head.next);
  head.next.next = head;
  head.next = undefined;
  return tmp;
}
2
# Node class 
class Node: 
   
    # Function to initialize the node object 
    def __init__(self, data): 
        self.data = data  # Assign data 
        self.next = None  # Initialize  
                          # next as null 
   
# Linked List class 
class LinkedList: 
     
    # Function to initialize the Linked  
    # List object 
    def __init__(self):  
        self.head = None
1
function LinkedListNode(value) {
  this.value = value;
  this.next = null;
}
let head = new LinkedListNode(10)
head.next = new LinkedListNode(25)
head.next.next = new LinkedListNode(46)

// Recursive
const reverse = (head) => {
 if (!head || !head.next) {
   return head;
 }
 let temp = reverse(head.next);
 head.next.next = head;
 head.next = undefined;
 return temp;
}
head = reverse(head)
0

New to Communities?

Join the community