Skip to content

Latest commit

 

History

History
51 lines (40 loc) · 1.55 KB

File metadata and controls

51 lines (40 loc) · 1.55 KB

存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除链表中所有存在数字重复情况的节点,只保留原始链表中 没有重复出现 的数字。

返回同样按升序排列的结果链表。

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

实现

/**
 * 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 (null == head || null == head.next) {
            return head;
        }

        // 先创建一个哑节点
        ListNode root = new ListNode(0, head);
        ListNode cur = root;

        while (cur.next != null && cur.next.next != null) {
            if (cur.next.val == cur.next.next.val) {
                int v = cur.next.val;
                while (null != cur.next && cur.next.val == v) {
                    cur.next = cur.next.next;
                }
            } else {
                cur = cur.next;
            }
        }

        return root.next;
    }
}