题目地址:
https://www.lintcode.com/problem/find-node-in-linked-list/description
给定一个单链表,再给定一个数,找出值为这个数的链表节点。代码如下:
public class Solution {
/*
* @param head: the head of linked list.
* @param val: An integer.
* @return: a linked node or null.
*/
public ListNode findNode(ListNode head, int val) {
// write your code here
while (head != null) {
if (head.val == val) {
return head;
}
head = head.next;
}
return head;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。