zoukankan      html  css  js  c++  java
  • [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

    思路:我们看当前节点的下一个是否等于val,如果等于的话,就把当前节点的next指向下个节点的next

     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     public ListNode removeElements(ListNode head, int val) {
    11         ListNode current = head;
    12         while (current!=null){
    13             if (current==head&&current.val==val){
    14                 head = head.next;     //如果是头节点的话,就移动头节点
    15                 current = head;
    16             }
    17             else if (current.next!=null&&current.next.val==val)
    18                 current.next = current.next.next;  //看当前节点的下一个的值是否为val
    19             else
    20                 current = current.next;
    21         }
    22     }
    23 }
  • 相关阅读:
    编译预处理命令define
    共享数据的包含const
    友元类,友元函数
    静态成员static
    this 指针
    构造函数与析构函数
    c++类的基础
    void指针和const指针
    c++基础
    组播的实现
  • 原文地址:https://www.cnblogs.com/David-Lin/p/7768667.html
Copyright © 2011-2022 走看看