[JavaScript 刷题] 链表 - 移除链表元素, leetcode 203

[JavaScript 刷题] 链表 - 移除链表元素, leetcode 203

github repo 地址: https://github.com/GoldenaArcher/js_leetcode,Github 的目录 大概 会更新的更勤快一些。

题目地址:203. Remove Linked List Elements

题目

如下:

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

解题思路

一般情况下会有这么几种可能性:

  1. 链表头部出现要去除的数字

    假设这里要去除的数字是 1,所有要移除的数字都在链表头部。

    1
    2
    1
  2. 链表中部出现要去除的数字

    假设这里要去除的数字是 2,所有要移除的数字都在链表中部。

    1
    2
    2

只要处理了这两个 special cases,那么剩下的就都不是问题了。

题目中需求说,依旧需要返回一个指向头部的结点,所以这道题也需要声名两个额外的结点指向头部,一个 head 用于遍历,一个 res 用于返回。

完了之后每次遍历 list1list2 时判断当前结点是否需要移除,如果是的话,跳到下一个;如果否,则更新遍历用的节点 head,让其指向当前结点,随后 head 指向 head.next

使用 JavaScript 解题

下面这个是比较平铺直叙地使用循环完成的解法,后面还有一种使用递归的解法。

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

  while (temp && temp.val === val) {
    
    
    temp = temp.next;
  }

  const res = temp;

  while (temp) {
    
    
    let next = temp.next;
    while (next && next.val === val) {
    
    
      next = next.next;
    }

    temp.next = next;
    temp = temp.next;
  }

  return res;
};

这个解法来自:3 line recursive solution

public ListNode removeElements(ListNode head, int val) {
    
    
        if (head == null) return null;
        head.next = removeElements(head.next, val);
        return head.val == val ? head.next : head;
}

同类型题

题目地址:83. Remove Duplicates from Sorted List

题目如下:

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

代码如下:

/**
 * 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 deleteDuplicates = function (head) {
    
    
  if (head === null || head.next === null) return head;

  const res = head;

  while (head && head.next) {
    
    
    if (head.next.val === head.val) {
    
    
      head.next = head.next.next;
    } else {
    
    
      head = head.next;
    }
  }

  return res;
};

猜你喜欢

转载自blog.csdn.net/weixin_42938619/article/details/125176975