JavaScript算法题实现-206-反转链表——腾讯面试题库

出题指数(最大5):⭐⭐⭐⭐⭐

题目

反转一个单链表。

示例:

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

进阶:

你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

LeetCode原题目指路

题解

迭代,利用三个指针:head、previous、current可以轻松实现

JavaScript实现

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

// 算法实现
function ListNode(val) {
  this.val = val;
  this.next = null;
}
var reverseList = function (head) {
  // 特殊情况
  if (head === null || head.next === null) return head;
  // 从第二个节点开始迭代反转
  // 注意这几句的顺序不能颠倒
  let previous = head;
  head = head.next;
  let current = head;
  previous.next = null;
  do {
    head = head.next;
    current.next = previous;
    previous = current;
    current = head;
  } while (head !== null)
  return previous;
};

// 测试数据
// 1->2->3->4->5->null
let h = new ListNode(1);
let n2 = new ListNode(2);
let n3 = new ListNode(3);
let n4 = new ListNode(4);
let n5 = new ListNode(5);
h.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;

function showLink(head) {
  let temp = head;
  while (temp != null) {
    console.log(temp.val);
    temp = temp.next;
  }
}
showLink(h);
let h2 = reverseList(h);
showLink(h2);

做题心得

笔者的朋友在Microsoft一面的时候碰到了这个题,这题考的频率还蛮高的。本身题目也不是很难,细心点就好。

当年数据结构的老师讲这个题的时候非要让我们只用两个指针,一下子巨绕,简直降维打击=-=,用三个指针牺牲存储空间拯救脑细胞不好嘛233

猜你喜欢

转载自www.cnblogs.com/zhoujiayingvana/p/12686936.html