leetcode83.Remove Duplicates from Sorted Lists

来源:互联网 发布:apache ant.jar下载 编辑:程序博客网 时间:2024/06/03 17:45
这个题要求删除已排好序的链表中的重复项, 例如1->1->2->3->3删除之后就是1->2->3。思路是令p指向当前节点每次循环找到一个q.next.val != q.val, 然后令p.next = q.next  就可以实现删除p.val对应的重复项了。
    public ListNode deleteDuplicates(ListNode head) {        if (head == null || head.next == null)            return head;        ListNode p = head;        while (p != null && p.next != null) {            ListNode q = p;            while (q.next != null && q.next.val == q.val) {                q = q.next;            }            p.next = q.next;                p = p.next;        }        return head;    }