LeetCode笔记:反转链表

问题

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

示例:

输入: 1->2->3->4->5->NULL

输出: 5->4->3->2->1->NULL

限制:

0 <= 节点个数 <= 5000

解法

思路:

循环整个链表,每次循环新建一个父级节点指向当前节点,最后生成的父节点就是反转后的头节点

代码:

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function (head) {
  let next = null;
  // 循环至链表尾部结束
  while (head != null) {
    // 生成父节点,带上字节点
    const node = {
      val: head.val,
      next: next,
    };

    // 移动到下一个位置
    head = head.next;
    next = node;
  }

  return next;
};

测试:

//定义一个 1->2->3->4->5 的链表
var list = {
  val: 1,
  next: {
    val: 2,
    next: {
      val: 3,
      next: {
        val: 4,
        next: {
          val: 5,
          next: null,
        },
      },
    },
  },
};
//反转链表
reverseList(list); //输出:5->4->3->2->1

参考

评论