删除链表中重复的结点

删除链表中重复的结点

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


/*
 public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
    public ListNode deleteDuplication(ListNode pHead)
    {
        if(pHead==null||pHead.next==null){
            return pHead;
        }
        ListNode thisNode,nextNode,head;
        head=new ListNode(0);
        head.next=pHead;
        /*
        构建head,避免了删除头节点的问题
        */
        thisNode=head;
        nextNode=thisNode.next.next;
        while(nextNode!=null){
            while(nextNode!=null &&thisNode.next.val==nextNode.val){
                nextNode=nextNode.next;
            }
            if(nextNode==null){
                thisNode.next=null;
                /*
                如果nextNode后移了,不符合 nextNode=thisNode.next.next的关系了:注意此时thisNode是不移动的,nextNode移动一次,就又符合关系了
                */
            }else if(nextNode!=thisNode.next.next){
                thisNode.next=nextNode;
                nextNode=nextNode.next;
            }else{
                /*
                如果一样,就各移一位
                */
                nextNode=nextNode.next;
                thisNode=thisNode.next;
            }
        }
        return head.next;
    }
}

这里用到了三个辅助节点,还是比较多的

这里一个重要的思想就是构造了辅助头节点,从而避免了删除头节点的问题,值得借鉴

posted @ 2020-03-08 01:12  别再闹了  阅读(82)  评论(0)    收藏  举报