题目描述

  1. 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

分析

  1. 注意 : 重复的节点不保留

代码

  1. /*
  2. public class ListNode {
  3. int val;
  4. ListNode next = null;
  5. ListNode(int val) {
  6. this.val = val;
  7. }
  8. }
  9. */
  10. public class Solution {
  11. /**
  12. * @param head
  13. * @return
  14. */
  15. public ListNode deleteDuplication(ListNode head) {
  16. if (head == null) {
  17. return head;
  18. }
  19. ListNode toolNode = new ListNode(-1);
  20. toolNode.next = head;
  21. ListNode pre = toolNode;
  22. ListNode last = toolNode.next;
  23. while (last != null) {
  24. if (last.next != null && last.val == last.next.val) {
  25. while (last.next != null && last.val == last.next.val) {
  26. last = last.next;
  27. }
  28. pre.next = last.next;
  29. last = last.next;
  30. } else {
  31. pre=pre.next;
  32. last=last.next;
  33. }
  34. }
  35. // 1 1 1
  36. // 1 2 3 4
  37. // x 1 1 1 1 2 2 3 4 4 5
  38. // pre last
  39. return toolNode.next;
  40. }
  41. }

相关例题