描述
在链表中找值为 value 的节点,如果没有的话,返回空(null)。
如果有多个相同的结点,返回找到的第一个结点
样例
样例 1:
输入: 1->2->3 and value = 3
输出: 最后一个结点
样例 2:
输入: 1->2->3 and value = 4
输出: null
C++:
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: the head of linked list.
* @param val: An integer.
* @return: a linked node or null.
*/
ListNode* findNode(ListNode *head, int val) {
// write your code here
while(head!=NULL){
if(head->val==val)
return head;
else
head=head->next;
}
return NULL;
}
};
Accepted 100%
82 ms时间消耗 5.59 MB空间消耗 您的提交打败了91.40 %的提交
C++:
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: the head of linked list.
* @param val: An integer.
* @return: a linked node or null.
*/
ListNode* findNode(ListNode *head, int val) {
// write your code here
for(;head!=NULL;head=head->next)
{
if(head->val==val)
return head;
}
return NULL;
}
};
Accepted 100%
61 ms时间消耗 5.36 MB空间消耗 您的提交打败了99.00 %的提交