zoukankan      html  css  js  c++  java
  • Lintcode225-Find Node in Linked List-Naive

    225. Find Node in Linked List

    Find a node with given value in a linked list. Return null if not exists.

    Example

    Example 1:

    Input:  1->2->3 and value = 3
    Output: The last node.
    

    Example 2:

    Input:  1->2->3 and value = 4
    Output: null
    

    Notice

    If there are multiple nodes of the same value return the first one.

    1. for循环

    错误代码:

    public ListNode findNode(ListNode head, int val) {
            for (head; head != null; head = head.next) {
                if (head.val == val) {
                    return head;
                }
            return null;
            }
        }

    error: not a statement
    for (head; head != null; head = head.next) {

    for循环语法

    for(初始化; 布尔表达式; 更新) {
        //代码语句
    }

    最先执行初始化步骤。可以声明一种类型,但可初始化一个或多个循环控制变量,也可以是空语句。也就是说初始化的时候,必须声明循环变量的类型

    只写一个 head是错的,没有声明变量类型。

    正确代码:

    public ListNode findNode(ListNode head, int val) { 
            for (ListNode node = head; node != null; node = node.next) {
                if (node.val == val) {
                    return node;
                }
            }
            return null;
        }  

    2. while循环

    public ListNode findNode(ListNode head, int val) {
            while(head != null) {
                if (head.val == val) {
                    return head;
                } else {
                    head = head.next;
                }
            }
            return null;
        }

    while循环是直接用head,这是跟while的语法有关:

    while( 布尔表达式 ) {
      //循环内容
    }

    while后面放的是一个布尔表达式

  • 相关阅读:
    git 通过 fork 解决代码冲突
    vue-cli3.0 多页面和单页面的配置以及相互之间的切换
    关于切换环境变量的问题( 以vue-cli3.0 为例)
    vue-router 钩子
    Android eMMC 分区详解(转载)
    《PE总结 》– 重定位表(转载)
    Linux 文件系统
    爬虫登录,立FLAG
    ios tweak 开发
    ios app 砸壳
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/10740234.html
Copyright © 2011-2022 走看看