首页 > 其他 > 详细

Lintcode225-Find Node in Linked List-Naive

时间:2019-04-20 12:25:31      阅读:102      评论:0      收藏:0      [点我收藏+]

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

 

Lintcode225-Find Node in Linked List-Naive

原文:https://www.cnblogs.com/Jessiezyr/p/10740234.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!