current position:Home>Sword finger offer (17) -- reverse linked list (idea and code)

Sword finger offer (17) -- reverse linked list (idea and code)

2021-08-27 08:53:23 Beihai sky

This is my participation 8 The fourth of the yuegengwen challenge 17 God , Check out the activity details :8 Yuegengwen challenge

subject Define a function , Enter the head node of a linked list , Invert the linked list and output the head node of the inverted linked list .


So let's define a cur The pointer , Point to the head node , Let me define one more pre The pointer , Initialize to null.

And then it's going to start reversing , First of all, put cur->next For nodes tmp Save the pointer , That is to save this node .

Why save this node , Because the next thing to change cur->next Of points to , take cur->next Point to pre , The first node has been reversed .

Next , It's the following code logic , Keep moving pre and cur The pointer .

Last ,cur The pointer has pointed to null, The loop ends , The list has been reversed . At this point we return pre Just a pointer ,pre The pointer points to the new header .

var reverseList = function(head) {
    var prev = null;
    var curr = head;
    while(curr !== null) {
        let cnext =; = prev 
        prev = curr
        curr = cnext

    return prev

 Copy code 

copyright notice
author[Beihai sky],Please bring the original link to reprint, thank you.

Random recommended