LeetCode-82:删除排序链表中的重复元素(Java语言实现)

/**
 * 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 s = new ListNode(-1, head);
        ListNode p1 = s;
        ListNode p2 = head;
        ListNode p3 = head.next;

        while (p3 != null) {

            if (p3.val == p2.val) {

                while (p3 != null && p3.val == p2.val) {

                    p3 = p3.next;

                }
                p1.next = p3;
                p2 = p3;
                if (p3 != null) {
                    p3 = p3.next;
                }

            }

            else {
                p3 = p3.next;
                p2 = p2.next;
                p1 = p1.next;
            }

        }
        return s.next;
    }
}

你可能感兴趣的:(leetcode,链表,java,数据结构,算法)