java刪除鏈表中重複的節點(保留一個節點)

兩種方法實現:

package cn.exercise.list;
import java.util.HashMap;
/**
 * 刪除鏈表重複節點(重複節點只保留一個)
 */
public class DeleteDuplecate {
    /**
     * HashMap,時間複雜度o(n)
     * @param head
     * @return
     */
    public static ListNode deleteDulp(ListNode head){
        if(head==null || head.next==null)
            return head;
        HashMap<Integer,Integer> map=new HashMap<Integer, Integer>();
        ListNode p=new ListNode(-1);//加一個頭結點
        p.next=head;
        ListNode pre=p;//兩個一前一後臨時指針
        ListNode cur=p.next;
        while(pre!=null && pre.next!=null){
            if(map.containsKey(cur.val)){
                pre.next=cur.next;
                cur=cur.next;
            }else{
                map.put(cur.val,1);
                pre=cur;
                cur=cur.next;
            }
        }
        return p.next;
    }
    /**
     * 雙重循環遍歷鏈表,時間複雜度o(n^2)
     * @param head
     * @return
     */
    public static ListNode deleteDulp2(ListNode head){
        if(head==null || head.next==null)
            return head;
        ListNode p=head;
        ListNode root=p;
        while(p!=null){
            ListNode q=p;
            while(q.next!=null){
                if(p.val==q.next.val){
                    q.next=q.next.next;
                }else{
                    q=q.next;
                }
            }
            p=p.next;
        }
        return root;
    }
    public static void main(String[] args){
        ListNode root=new ListNode(1);
        ListNode b=new ListNode(2);
        ListNode c=new ListNode(4);
        ListNode d=new ListNode(2);
        ListNode e=new ListNode(5);
        ListNode f=new ListNode(4);
        ListNode g=new ListNode(3);
        ListNode h=new ListNode(5);
        root.next=b;
        b.next=c;
        c.next=d;
        d.next=e;
        e.next=f;
        f.next=g;
        g.next=h;
        while(root!=null){
            System.out.print(root.val+" ");
            root=root.next;
        }
        System.out.print("after:");
        ListNode pre=deleteDulp2(root);

        while(pre!=null){
            System.out.print(pre.val+" ");
            pre=pre.next;
        }
    }
}
before:1 2 4 2 5 4 3 5
結果:
after:1 2 4 5 3 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章