LeetCode--83. Remove Duplicates from Sorted List & 82. Remove Duplicates from Sorted List II

题目链接:https://leetcode.com/problems/remove-duplicates-from-sorted-list/

https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

题目一:要求在升序链表中删去再次出现的节点,题目二要求将链表中出现频次超过一次的数字的节点(第一次出现的节点也删除)给删掉,这两题目小有区别,但思路清晰,手起刀落,砍瓜切菜。

题目一:需要两个引用指针p,q确定重复数字出现的范围。

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        
        
        if(head==null || head.next==null)
            return head;
        ListNode virtual=new ListNode(Integer.MIN_VALUE);
        virtual.next=head;
        
        ListNode p=head,q=null;
        
        while(p.next!=null)
        {
            q=p;
            while(q.next!=null && q.next.val==p.val)
                q=q.next;
            if(p!=q)
                p.next=q.next;
            p=p.next;
            if(p==null)
                break;
        }
        return virtual.next; 
    }
}

题目二的效率最高的思路很简单,现在链表题目特别熟练,基本都能1-2次AC,注意corner cases和常用tricks。除了需要两个引用指针来确定连续重复数字的范围,还需要一个前驱引用来完成删除操作。代码如下:

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

猜你喜欢

转载自blog.csdn.net/To_be_to_thought/article/details/85782441