57 删除链表中重复的节点

题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

突然发现,这是一个意思。根本不是两个指针和一个指针的问题。重点在于头结点的保存。一个是移动了头结点,另一个是声明了一个新的节点,让它指向头结点!关键在于保存上一个节点pre!

首先一点,只要.next了,一定要判断当前节点是不是null;
如果开始的几个节点是一样的;;;
如果一样的节点数量超过两个;

public class Solution {
    public ListNode deleteDuplication(ListNode pHead)
    {
        if(pHead == null)
            return null;
        ListNode slow = pHead;
        ListNode fast = slow.next;
        if(fast == null)
            return pHead;        
        ListNode pre = slow;
        while(slow.val == fast.val){
             while(slow.val == fast.val){
                 fast = fast.next;
                 if(fast == null){
                     return null;
                 }
             }
            pHead = fast;
            slow = pHead;
            fast = slow.next;
            if(fast == null)
                return pHead;
        }


        while(fast != null){
            if(slow.val != fast.val){
                pre = slow;
                slow = fast;
                fast = fast.next;
            }else{
                while(fast.val == slow.val){
                    fast = fast.next;
                    if(fast == null){
                        break;
                    }
                }
                pre.next = fast;
                slow = pre;
            }                                

        }
        return pHead;
    }
}

不要过度的使用两个指针,其实一个指针也能做出来。

public class Solution {
    public ListNode deleteDuplication(ListNode pHead)
    {
        if(pHead == null)
            return null;
        ListNode p = pHead;
        ListNode ph = new ListNode(0);
        ListNode pre = ph;
        ph.next = pHead;

        while(p != null){
            ListNode tmp = p.next;
            int value = p.val;
            if(tmp == null)
                return ph.next;
            if(tmp.val == value){
                 while(tmp != null && tmp.val == value){
                    tmp = tmp.next;
                    if(tmp == null){
                        pre.next = tmp;
                    }               
                }
                p = tmp;
                pre.next = p;
            }else{
                pre = p;
                p = tmp;
            }                                  
        }                       
        return ph.next;
    }
}

猜你喜欢

转载自blog.csdn.net/xuchonghao/article/details/80510707
57
今日推荐