1. 概述

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1: 输入: 1->1->2

输出: 1->2

示例 2:

输入: 1->1->2->3->3

输出: 1->2->3

2. 解题

  1. <?php
  2. class ListNode {
  3. /** @var int */
  4. public $val = 0;
  5. /** @var ListNode */
  6. public $next = null;
  7. function __construct($val) { $this->val = $val; }
  8. }
  9. class Solution {
  10. /**
  11. * @param ListNode $head
  12. * @return ListNode
  13. */
  14. public function deleteDuplicates($head) {
  15. $p = $head;
  16. $checkVal = $head->val;
  17. while ($p->next) {
  18. if ($p->next->val == $checkVal && $p->next->next) {
  19. $p->next = $p->next->next;
  20. } else {
  21. $checkVal = $p->next->val;
  22. $p = $p->next;
  23. }
  24. }
  25. return $head;
  26. }
  27. }
  28. $head = new ListNode(1);
  29. $head->next = new ListNode(1);
  30. $head->next->next = new ListNode(2);
  31. $head->next->next->next = new ListNode(3);
  32. $head->next->next->next->next = new ListNode(4);
  33. $cls = new Solution();
  34. $ret = $cls->deleteDuplicates($head);
  35. print_r($ret);