83. 删除排序链表中的重复元素

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode dummy = new ListNode(0, head);
        ListNode p = dummy.next, q = p.next;
        while (p != null && q != null) {
            if (q.val == p.val) {
                p.next = q.next;
                q = p.next;
            } else {
                p = p.next;
                q = q.next;
            }
        }
        return dummy.next;
    }
}

注意链表的虚拟头结点的声明:

ListNode dummy = new ListNode(0, head);

你可能感兴趣的:(LeetCode,链表,数据结构)