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后面放的是一个布尔表达式

  • 相关阅读:
    Feign Ribbon Hystrix 关系剖析
    Activiti 分布式方案实现探讨
    Flink任务架构分析
    Activiti 数据库表梳理
    负载均衡方案优缺点探讨
    公文流转系统
    css美化界面
    动手动脑(二)
    csslayui树练习
    css点名
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/10740234.html
Copyright © 2011-2022 走看看