leetcode 203. 移除链表元素

leetcode 每日一题 203. 移除链表元素

我的思路

使用指针,标记当前结点,如果当前结点的值等于给定的值,那么删除这个结点。怎么删除呢?这个结点的前一个结点的 next 直接指向这个结点的后一个结点,这样就可以删除掉本结点。
我使用两个指针,一个标记本结点,另一个标记本结点的前一个结点。当然啦,还有一个头结点,最后用于返回。

/**
 * 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) {
  p = head; //指向头指针,最后用于返回
  while (p != null && p.val == val) {
    p = p.next == null ? null : p.next;
  }
  if (p == null) return p; //空链表,直接返回
  pre = p; //指向本结点的前一个结点
  temp = pre.next == null ? null : pre.next; //目前结点指针,用于查询更改
  while (temp != null) {
    if (temp.val == val) {
      pre.next = temp.next == null ? null : temp.next;
      temp = temp.next == null ? null : temp.next;
    } else {
      temp = temp.next;
      pre = pre.next;
    }
  }
  return p;
};

题解的其他思路

官方题解

  1. 递归
    因为链表具有递归性质,所以可以用递归解该题。

    var removeElements = function (head, val) {
      if (head === null) {
        //结点为空,返回;递归的终止条件。
        return head;
      }
      head.next = removeElements(head.next, val);
      return head.val === val ? head.next : head; //判断head的值是否等于val,若是,则返回该节点的next,否则返回该结点。
    };
    
  2. 迭代
    其实感觉我用的方法就是迭代。不过感觉题解更加的精简。

    var removeElements = function (head, val) {
      const dummyHead = new ListNode(0); //虚拟头结点
      dummyHead.next = head;
      let temp = dummyHead; //temp表示当前结点
      while (temp.next !== null) {
        if (temp.next.val == val) {
          temp.next = temp.next.next;
        } else {
          temp = temp.next;
        }
      }
      return dummyHead.next; //返回虚拟头结点的next
    };
    

总结

  1. 又复习了链表操作,链表的定义具有递归的性质,在以后的做题过程中需要思考这一点。
  2. 在链表中,虚拟头结点在解题中很有必要。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值