当前位置: 面试刷题>> 无序链表的重复项删除 (经典算法题500道)
### 题目描述补充
题目:**无序链表的重复项删除**
给定一个单链表的头节点 `head`,链表中包含整数类型的节点值,且链表中节点的值可能重复。请编写一个函数,删除链表中所有重复的元素,使得每个元素只出现一次,并返回修改后的链表的头节点。
注意:
1. 链表中的节点定义可能如下(以Python为例,其他语言类似):
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
```
2. 题目要求修改链表本身,而不是返回一个新的链表。
3. 假设链表中至少包含一个节点,且节点的值在 `[-1000, 1000]` 的范围内。
### Python 代码示例
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def deleteDuplicates(head):
if not head or not head.next:
return head
current = head
while current and current.next:
if current.val == current.next.val:
# 发现重复,删除重复节点
current.next = current.next.next
else:
current = current.next
return head
# 示例使用
# 创建链表 1->2->3->3->4->4->5
node5 = ListNode(5)
node4 = ListNode(4, node5)
node4_dup = ListNode(4, node4)
node3 = ListNode(3, node4_dup)
node3_dup = ListNode(3, node3)
node2 = ListNode(2, node3_dup)
node1 = ListNode(1, node2)
# 删除重复项
result_head = deleteDuplicates(node1)
# 辅助函数打印链表
def printList(node):
while node:
print(node.val, end=" ")
node = node.next
print()
printList(result_head) # 输出应为 1 2 3 4 5
```
### PHP 代码示例
```php
class ListNode {
public $val;
public $next;
function __construct($val = 0, $next = null) {
$this->val = $val;
$this->next = $next;
}
}
function deleteDuplicates($head) {
if (!$head || !$head->next) {
return $head;
}
$current = $head;
while ($current && $current->next) {
if ($current->val == $current->next->val) {
$current->next = $current->next->next;
} else {
$current = $current->next;
}
}
return $head;
}
// 示例使用
// 假设已经通过某种方式创建了链表
// ...
// 删除重复项并打印结果(这里省略链表创建的代码)
```
### JavaScript 代码示例
```javascript
class ListNode {
constructor(val = 0, next = null) {
this.val = val;
this.next = next;
}
}
function deleteDuplicates(head) {
if (!head || !head.next) {
return head;
}
let current = head;
while (current && current.next) {
if (current.val === current.next.val) {
current.next = current.next.next;
} else {
current = current.next;
}
}
return head;
}
// 示例使用
// 创建链表 1->2->3->3->4->4->5
let node5 = new ListNode(5);
let node4 = new ListNode(4, node5);
let node4_dup = new ListNode(4, node4);
let node3 = new ListNode(3, node4_dup);
let node3_dup = new ListNode(3, node3);
let node2 = new ListNode(2, node3_dup);
let node1 = new ListNode(1, node2);
// 删除重复项
let resultHead = deleteDuplicates(node1);
// 辅助函数打印链表
function printList(node) {
let result = '';
while (node) {
result += `${node.val} `;
node = node.next;
}
console.log(result.trim());
}
printList(resultHead); // 输出应为 1 2 3 4 5
```
**码小课网站中有更多相关内容分享给大家学习**,包括链表操作、算法进阶等丰富资源。