strategies to reverse a linked list in JavaScript

后端 未结 6 1363
一个人的身影
一个人的身影 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:35

    Reversing the SinglyLinkedList: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL

    To understand The Solution we have to keep track of previous head and next variables for example in above input Head = 1 ; next = 2 we don't have previous so assume previous = null loop the list till head is not null. reverse the connections(previous and next) of head. Below is the code

    var reverseList = function(head) {
        let previous = null;
        while(head !== null){
            let next = head.next;
            head.next = previous;
            previous= head
            head = next;
        }
        return previous;
        
    };

提交回复
热议问题