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