• LeetCode 203. Remove Linked List Elements (移除链表中的项)


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

    Example
    Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
    Return: 1 --> 2 --> 3 --> 4 --> 5


    题目标签:Linked List

      题目给了我们一个 链表 和一个 val,让我们把链表中 等于 val 的点都去除。

      情况1: 如果head.val == val,那么设 head = head.next,同时cursor 也要重新设定。

      情况2: 如果cursor.next.val == val 那么把cursor 连到 下下个点,跳过中间点。

      情况3: 如果cursor.next.val != val 的话,那么移动cursor 去下一个点。

    Java Solution:

    Runtime beats 50.37% 

    完成日期:06/10/2017

    关键词:singly-linked list

    关键点:检查cursor.next.val

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 class Solution 
    10 {
    11     public ListNode removeElements(ListNode head, int val) 
    12     {
    13         ListNode cursor = head;
    14         
    15         while(cursor != null)
    16         {
    17             if(head.val == val)
    18             {
    19                 head = head.next;
    20                 cursor = head;
    21             }
    22             else if(cursor.next != null && cursor.next.val == val)
    23             {
    24                 ListNode valNode = cursor.next;
    25                 cursor.next = valNode.next;
    26                 valNode.next = null;
    27             }
    28             else
    29                 cursor = cursor.next;
    30             
    31         }
    32         
    33         return head;
    34     }
    35 }

    参考资料:N/A

    LeetCode 题目列表 - LeetCode Questions List

    题目来源:https://leetcode.com/

  • 相关阅读:
    Docker容器管理神器
    查看MySQL连接状态
    使用 Docker 镜像安装 Radicale3
    Java文档注释的使用
    Hibernate依赖问题
    WPF HelixToolkit 3D
    二分法
    比较 React vue, 单向绑定 双向绑定 优缺点
    7 个杀手级的 JS 一行代码
    js中??和?.的意思
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7927044.html
Copyright © 2020-2023  润新知