zoukankan      html  css  js  c++  java
  • 0203. Remove Linked List Elements (E)

    Remove Linked List Elements (E)

    题目

    Remove all elements from a linked list of integers that have value val.

    Example:

    Input:  1->2->6->3->4->5->6, val = 6
    Output: 1->2->3->4->5
    

    题意

    将给定链表中所有含有指定值的结点删除。

    思路

    注意需要连续删除结点的情况。


    代码实现

    Java

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode removeElements(ListNode head, int val) {
            ListNode dumb = new ListNode(0);
            dumb.next = head;
            ListNode pre = dumb;
            ListNode cur = head;
    
            while (cur != null) {
                if (cur.val == val) {
                    pre.next = cur.next;
                    cur = cur.next;
                } else {
                    pre = pre.next;
                    cur = cur.next;
                } 
            }
    
            return dumb.next;
        }
    }
    

    JavaScript

    /**
     * @param {ListNode} head
     * @param {number} val
     * @return {ListNode}
     */
    var removeElements = function (head, val) {
      let dummy = new ListNode(0, head)
      let pre = dummy
      let cur = head
      while (cur) {
        if (cur.val === val) {
          pre.next = cur.next
        } else {
          pre = cur
        }
        cur = cur.next
      }
      return dummy.next
    }
    
  • 相关阅读:
    【转】size_t和ssize_t
    WCF订票系统DEMO
    VS2008显示解决方案的方法
    一些好用的开源控件
    SQL 的Over 子句
    Sql2005高效分页语句
    使用winform的showdialog小心内存泄漏
    字符串连接类(Javascript)
    SharpZipLib 的使用
    浅谈持久化
  • 原文地址:https://www.cnblogs.com/mapoos/p/13352934.html
Copyright © 2011-2022 走看看