206 反转链表 JavaScript实现

138 阅读1分钟

反转链表

题目链接

一、有关JS基础知识

1、定义节点

function ListNode(val,next){
	this.val = (val===undefined ? 0 : val)
	this.next = (next===undefined ? null :next)
}

	

2、指针的用法

// 声明指针,一般使用块级作用域的let
// 指针pre
let pre = Null;

二、思路

1、迭代法

图解反转链表

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */

// 定义一个函数表达式
var reverseList = function(head) {
    // 声明指针 -- 块级作用域
    let pre = null;
    let cur = head;
    
    while(cur){
        // 声明一个常量
        let temp = cur.next;
        
        // 反转指针
        cur.next = pre;
        
        // 移动指针
        pre = cur;
        cur = temp;
    }
    // 最后cur会指向null,所以返回pre. 
    // 如果是返回pre.next,就是除了最后一个元素的前面的链
    return pre;

};

在这里插入图片描述

2、递归法

递归ppt演示 当反转链表的时候,是从最后一个节点开始反转的。

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */

// 把这个函数看作是递归函数
var reverseList = function(head) {
    // 3、递归的结束:当把最后一个节点放入递归的时候,结束. head.next == nul 
    // 还要防止空节点的情况 head == null
    if(head == null || head.next == null){
        return head
    }

    // 2、开始递归,把head节点后面的节点放入递归
    let newHead = reverseList(head.next)

    // 1、单层递归逻辑
    head.next.next = head
    head.next = null

    return newHead
};