地址:https://leetcode-cn.com/problems/remove-duplicate-node-lcci/
<?php /** 面试题 02.01. 移除重复节点 编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。 示例1: 输入:[1, 2, 3, 3, 2, 1] 输出:[1, 2, 3] 示例2: 输入:[1, 1, 1, 1, 2] 输出:[1, 2] 提示: 链表长度在[0, 20000]范围内。 链表元素在[0, 20000]范围内。 */ /** * 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 removeDuplicateNodes($head) { if($head == null || $head->next == null) return $head; $dummyhead = new ListNode(0); $cur = $dummyhead; $visited = []; while($head){ if(!isset ($visited[$head->val])){ $visited[$head->val] = true; $cur->next = new ListNode($head->val); $cur = $cur->next; } $head = $head->next; } return $dummyhead->next; } }