1. 程式人生 > >刪除連結串列中重複的結點(java版)

刪除連結串列中重複的結點(java版)

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

【解題思路1】
//1. 遍歷當前連結串列,用linkedHashMap儲存每個結點的出現次數。
//2. 再次遍歷原連結串列,只連接出現次數為1的節點。
//3. 設定一個標誌,用來設定頭結點,防止頭結點即重複的情況。

import java.util.LinkedHashMap;
public class Solution {
    public
ListNode deleteDuplication(ListNode pHead) { if(pHead==null){ return null; } boolean flag = true; ListNode inx=pHead, current=null; LinkedHashMap <Integer, Integer> map = new LinkedHashMap<Integer, Integer>(); while(inx!=null
){ if(map.containsKey(inx.val)){ map.put(inx.val, map.get(inx.val)+1); }else{ map.put(inx.val, 1); } inx = inx.next; } inx = pHead; pHead = null; //重新置空,適用於所有結點值都相同的情況 while(inx != null
){ if(flag==true && map.get(inx.val)==1){ //設定頭結點 pHead = inx; current = inx; flag = false; }else if(flag==false && map.get(inx.val)==1){ current.next = inx; current = inx; } inx = inx.next; } if(current != null){ current.next = null; //去掉尾巴,適用於最後的幾個結點重複的情況 } return pHead; } }

【解題思路2】
//1.把當前結點的前一個結點(pre)和後面值比當前結點的值要大的結點相連。

public class Solution {
    public ListNode deleteDuplication(ListNode pHead)
    {
        if(pHead == null || pHead.next == null) return pHead;
        ListNode temp = new ListNode(-1);
        temp.next = pHead;
        ListNode curNode = pHead;
        ListNode pre = temp;
         while(curNode != null && curNode.next != null){
            ListNode next = curNode.next;
            if(curNode.val == next.val){
                while(next != null && curNode.val == next.val){
                    next = next.next;
                }
                pre.next = next;
                curNode = next;
            }else{
                pre = curNode;
                curNode = curNode.next;
            }
        }
        return temp.next;
    }
}