JavaScript algorithm question realization-206-reverse linked list——Tencent interview question bank

Question index (maximum 5): ⭐⭐⭐⭐⭐

topic

Reverse a singly linked list.

Example:

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

Advanced:

You can reverse the list iteratively or recursively. Can you solve this problem in two ways?

LeetCode original question guide

answer

Iteration, using three pointers: head, previous, current can be easily achieved

JavaScript implementation

/**
 * 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);

Experience

My friend encountered this question when he was at Microsoft. The frequency of this question is quite high. The topic itself is not difficult, just be careful.

When the teacher of the data structure talked about this problem, we had to use only two pointers, and it was a big round, which was a dimensionality reduction. =-=, Using three pointers to sacrifice storage space to save brain cells is not good

Guess you like

Origin www.cnblogs.com/zhoujiayingvana/p/12686936.html