1. 程式人生 > >劍指offer(四十三)之刪除連結串列中重複的結點

劍指offer(四十三)之刪除連結串列中重複的結點

題目描述

在一個排序的連結串列中,存在重複的結點,請刪除該連結串列中重複的結點,重複的結點不保留,返回連結串列頭指標。 例如,連結串列1->2->3->3->4->4->5 處理後為 1->2->5

程式碼1:

import java.util.*;
public class Solution {
    public ListNode deleteDuplication(ListNode pHead)
    {
        if(pHead == null) return null;
        //定義一個連結串列,存放所有節點的值
        ArrayList<Integer> list = new ArrayList<Integer>();
        //定義一個頭指標
        ListNode p = pHead;
        list.add(p.val);
        while(p.next != null)
        {
            //滑動指標
            p = p.next;
            list.add(p.val);
        }
        //取出存在不重複的值
        ArrayList<Integer> list2 = new ArrayList<Integer>();
        for(int i : list)
        {
            int count = 0;
            for(int j : list)
            {
                if(i == j) count ++;
            }
            if(count == 1) list2.add(i);
        }
        //重建連結串列
        if(list2.size() == 0) return null;
        ListNode pHead2,p2;
        pHead2 = new ListNode(list2.get(0));
        p2 = pHead2;
        for(int i = 1;i < list2.size();i ++)
        {
            p2.next = new ListNode(list2.get(i));
            p2 = p2.next;
        }
        return pHead2;

    }
}
程式碼2:
public class Solution {
    public ListNode deleteDuplication(ListNode pHead)
    {
        if (pHead == null) {
            return null;
        }
        ListNode headNode = new ListNode(0);
        headNode.next = pHead;
        ListNode pre = headNode;
        ListNode p = pHead;
        while(p != null && p.next != null){
            if(p.val == p.next.val){
                int temp = p.next.val;
                while(p != null && p.val == temp){
                    p = p.next;
                }
                pre.next = p;
            }else{
                pre = p;
                p = p.next;
            }
        }
        return headNode.next;
    }
}