Find Node in Linked List

题目:

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

Given 1->2->3 and value = 3, return the last node.
Given 1->2->3 and value = 4, return null.

分析:

解法:

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
        ListNode res = null;
        while (head != null) {
            if (head.val == val) {
                res = head;
                break;
            }
            head = head.next;
        }
        return res;
    }  
}

results matching ""

    No results matching ""