1. 概述

给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中没有重复出现的数字。

示例 1:

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

输出: 1->2->5

示例 2:

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

输出: 2->3

2. 解题

  1. <?php
  2. class ListNode
  3. {
  4. public $val = 0;
  5. /** @var ListNode */
  6. public $next = null;
  7. function __construct($val)
  8. {
  9. $this->val = $val;
  10. }
  11. }
  12. class Solution
  13. {
  14. /**
  15. * @param ListNode $head
  16. * @return ListNode
  17. */
  18. public function deleteDuplicates($head)
  19. {
  20. if (!$head) {
  21. return null;
  22. }
  23. $dummy = new ListNode(0);
  24. $dummy->next = $head;
  25. $p = $dummy;
  26. // 循环迭代链表:条件是要移动指向当前的元素节点 或 改变下一个元素节点
  27. while ($p->next && $p->next->next) {
  28. if ($p->next->val == $p->next->next->val) {
  29. $num = $p->next->val;
  30. while ($p->next && $p->next->val == $num) {
  31. // 删除掉中间重复的元素(迭代:同时改变下一个元素节点,继续迭代使用)
  32. $p->next = $p->next->next;
  33. }
  34. } else {
  35. // (迭代:移动指向当前的元素节点)
  36. $p = $p->next;
  37. }
  38. }
  39. return $dummy->next;
  40. }
  41. }
  42. $head = new ListNode(1);
  43. $head->next = new ListNode(2);
  44. $head->next->next = new ListNode(3);
  45. $head->next->next->next = new ListNode(3);
  46. $head->next->next->next->next = new ListNode(4);
  47. $head->next->next->next->next->next = new ListNode(4);
  48. $head->next->next->next->next->next->next = new ListNode(5);
  49. $cls = new Solution();
  50. $ret = $cls->deleteDuplicates($head);
  51. print_r($ret);