LintCode: Find Node in Linked List

Find Node in Linked List



Similar Problems:


Description

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

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

Github: code.dennyzhang.com

Credits To: lintcode.com

Leave me comments, if you have better ways to solve.


  • Solution:
## Blog link: https://code.dennyzhang.com/find-node-in-linked-list
## Basic Ideas:
## Here we assume we only find the first node with the given value
## Complexity: Time O(n), Space O(1)
"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""


class Solution:
    """
    @param: head: the head of linked list.
    @param: val: An integer.
    @return: a linked node or null.
    """
    def findNode(self, head, val):
        p = head
        while p and p.val != val:
            p = p.next
        return p
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.