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

    Example 1:

    1. Input: 1->1->2
    2. Output: 1->2

    Example 2:

    1. Input: 1->1->2->3->3
    2. Output: 1->2->3

    题意

    对于有序链表中含有重复值的结点,只保留其中一个。。

    思路

    遍历就完事了。


    代码实现

    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. * int val;
    5. * ListNode next;
    6. * ListNode(int x) { val = x; }
    7. * }
    8. */
    9. class Solution {
    10. public ListNode deleteDuplicates(ListNode head) {
    11. ListNode cur = head;
    12. while (cur != null) {
    13. ListNode temp = cur.next;
    14. // 找到第一个与cur结点值不同的结点
    15. while (temp != null && temp.val == cur.val) {
    16. temp = temp.next;
    17. }
    18. cur.next = temp;
    19. cur = temp;
    20. }
    21. return head;
    22. }
    23. }