一、题目

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

给定一个排序链表,删除所有重复的元素每个元素只留下一个。

二、解题思路

遍历之,遇到当前节点和下一节点的值相同时,删除下一节点,并将当前节点next值指向下一个节点的next, 当前节点首先保持不变,直到相邻节点的值不等时才移动到下一节点。

三、解题代码

  1. /**
  2. * Definition for ListNode
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) {
  7. * val = x;
  8. * next = null;
  9. * }
  10. * }
  11. */
  12. public class Solution {
  13. /**
  14. * @param ListNode head is the head of the linked list
  15. * @return: ListNode head of linked list
  16. */
  17. public static ListNode deleteDuplicates(ListNode head) {
  18. ListNode curr = head;
  19. while (curr != null) {
  20. while (curr.next != null && curr.val == curr.next.val) {
  21. curr.next = curr.next.next;
  22. }
  23. curr = curr.next;
  24. }
  25. return head;
  26. }
  27. }