题意:
解题思路:
思路:双指针遍历:O(n)
1. 从前往后扫描,遇到有前后两个相同的节点,则直接删除后面的那个节点,否则指针移动到后面节点;
PHP代码实现:
/**
* Definition for a singly-linked list.
* class ListNode {
* public $val = 0;
* public $next = null;
* function __construct($val) { $this->val = $val; }
* }
*/
class Solution {
/**
* @param ListNode $head
* @return ListNode
*/
function deleteDuplicates($head) {
if (!$head) return null;
$cur = $head;
while ($cur->next) {
if ($cur->val == $cur->next->val) {
$cur->next = $cur->next->next;
} else {
$cur = $cur->next;
}
}
return $head;
}
}
GO代码实现:
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func deleteDuplicates(head *ListNode) *ListNode {
cur := head
for cur != nil && cur.Next != nil {
if cur.Val == cur.Next.Val {
cur.Next = cur.Next.Next
} else {
cur = cur.Next
}
}
return head;
}