当前位置: 面试刷题>> 在链表中找节点 (经典算法题500道)
### 题目描述补充
题目:在链表中找节点
给定一个单向链表和一个特定的值 `target`,编写一个函数来查找链表中是否存在值为 `target` 的节点。如果存在,则返回该节点的指针或引用;如果不存在,则返回 `null` 或一个表示不存在的值(取决于使用的编程语言)。
### 示例
假设链表的结构定义如下(以Python为例,其他语言类似):
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
```
### Python 示例代码
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def searchNode(head, target):
current = head
while current:
if current.val == target:
return current
current = current.next
return None
# 示例使用
# 构建链表 1 -> 2 -> 3 -> 4 -> 5
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
# 查找值为 3 的节点
target_node = searchNode(head, 3)
if target_node:
print(f"Found node with value {target_node.val}")
else:
print("Node not found")
```
### PHP 示例代码
```php
class ListNode {
public $val;
public $next;
function __construct($val = 0, $next = null) {
$this->val = $val;
$this->next = $next;
}
}
function searchNode($head, $target) {
$current = $head;
while ($current !== null) {
if ($current->val == $target) {
return $current;
}
$current = $current->next;
}
return null;
}
// 示例使用
// 构建链表 1 -> 2 -> 3 -> 4 -> 5
$head = new ListNode(1);
$head->next = new ListNode(2);
$head->next->next = new ListNode(3);
$head->next->next->next = new ListNode(4);
$head->next->next->next->next = new ListNode(5);
// 查找值为 3 的节点
$targetNode = searchNode($head, 3);
if ($targetNode !== null) {
echo "Found node with value " . $targetNode->val . "\n";
} else {
echo "Node not found\n";
}
```
### JavaScript 示例代码
```javascript
class ListNode {
constructor(val = 0, next = null) {
this.val = val;
this.next = next;
}
}
function searchNode(head, target) {
let current = head;
while (current) {
if (current.val === target) {
return current;
}
current = current.next;
}
return null;
}
// 示例使用
// 构建链表 1 -> 2 -> 3 -> 4 -> 5
let head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
// 查找值为 3 的节点
let targetNode = searchNode(head, 3);
if (targetNode) {
console.log(`Found node with value ${targetNode.val}`);
} else {
console.log("Node not found");
}
```
**码小课**网站中有更多关于链表操作和算法设计的相关内容分享给大家学习,欢迎访问以获取更多知识和技巧。