[Swipe the question bank] Sword refers to the 15th question of the Offer_ programming question (implemented by JavaScript), the linked list is reversed.

Topic: Input a linked list, after reversing the linked list, output the header of the new linked list.

Input: 1→2→3→4→5

Output: 5→4→3→2→1

Problem-solving ideas:

Define three variables pNode, pNext, and pre.

1. pNext is equal to pNode.next, which is the second node.

2. pNode.next (the second node) is equal to the bridge pre

3. Pre is equal to pNode, making the second node point to the first node.

 

4. pNode is equal to pNext. Let the three variables be equal to the second node, so that the next transformation

 

The final code is as follows:

/*function ListNode(x){
    this.val = x;
    this.next = null;
}*/
function ReverseList(pHead)
{
    pNext = pHead;
    pNode = pHead;
    var pre = null
    
    while(pNode){
        pNext = pNode.next;
        pNode.next = pre;
        pre = pNode;
        pNode = pNext;
    }
    
    return pre;
}

Solution two:

/*function ListNode(x){
    this.val = x;
    this.next = null;
}*/
function ReverseList(pHead)
{
    let newHead = null;
    while(pHead){
        let tmpNode= newHead;
        newHead = new ListNode(pHead.val);
        newHead.next = tmpNode;
        pHead = pHead.next;
    }
    return newHead;
}

 

Guess you like

Origin blog.csdn.net/weixin_42339197/article/details/99552772