strategies to reverse a linked list in JavaScript

后端 未结 6 1360
一个人的身影
一个人的身影 2020-12-13 20:23

I just struggled through a simple interview question: Please reverse a singly linked list.

While I failed to provide a working answer in time to save the interview,

6条回答
  •  佛祖请我去吃肉
    2020-12-13 20:48

    //O(n) | O(1) wherre n is the number of nodes in the linked list
    
    class Node{
      constructor(val){
        this.val = val;
        this.next = null;
      }
    }
    
    
    function reverseLinkedList(head) {
    
     if(!head) return null;
     
     let p1 = head;
     let p2 = null;
    	
    	while(p1){
    		let temp = p1.next;
    		p1.next = p2;
    		p2 = p1;
    		p1 = temp;
    	}
    	
    	return p2;
    }
    
    
    const a = new Node(1);
    a.next = new Node(2);
    a.next.next = new Node(3)
    
    console.log("Current Node",a);
    console.log("Reversed List",reverseLinkedList(a))

提交回复
热议问题