Wins the Offer (list) - delete duplicate node list

  (Delete duplicate node in the list) subject description:


In a sorted linked list nodes duplicate, delete the duplicate node list, the node does not retain repeated, returns the head pointer list. For example, the list 1-> 2-> 3-> 3-> 4-> 4-> 5 is treated 1-> 2-> 5


  Problem-solving ideas: duplicate nodes here is not reserved just repeat the nodes to be removed, so consider using the hash set method, the first judgment repetitive, duplicate elements are added to the hash set to go and then delete the duplicate elements.

  Using two pointers to the pre and cur, represented previous node and a current node.

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

    ListNode(int val) {
        this.val = val;
    }
}
*/
import java.util.*;
public class Solution {
    public ListNode deleteDuplication(ListNode pHead)
    {
        if(pHead == null){
            return null;
        }
        //先找出相同节点存入哈希set中
        HashSet<Integer> set = new HashSet<>();
        ListNode pre = pHead;
        ListNode cur = pHead.next;
        while(cur != null){
            if(cur.val == pre.val){
                set.add(cur.val);
            }
            CUR = pre; 
            CUR = cur.next; 
        } 
        // delete the same node 
        / ** 
        * delete the first node (the first node if it is a duplicate node) 
        * / 
        the while (PHEAD set.contains = null && (pHead.val)! ) { 
            PHEAD = pHead.next; 
        } 
        IF (PHEAD == null) { 
            return null; 
        } 
        / ** 
        * delete intermediate node 
        * / 
        pre = PHEAD; 
        CUR = pHead.next; 
        the while (CUR = null) {! 
            IF (set.contains (Cur.Val)) { 
                pre.next = cur.next; 
                CUR = cur.next; 
            } the else { 
                pre = CUR;
                = contribute cur.next; 
            } 
        } 
        Return Pet; 
    } 
}

   (1) deleting the first special attention node also needs to be empty when the determined head node, because the front of the head node is possible it is necessary to remove repeated, but after deleting the part of the header is empty and, if not empty judge's words:

IF (set.contains (pHead.val)) { 
      Pet = pHead.next; 
}

  There may be the case, repeat the head node deleted can not afford:

         

  So need is:

while(pHead!=null&&set.contains(pHead.val)){
     pHead = pHead.next;
}
if(pHead == null){
     return null;
}

  (2) There is to delete the current repeating elements when use is pre.next = cur.next ;, based on the current element cur, cur because the current set of repeat elements inside the set, need to be removed.

Guess you like

Origin www.cnblogs.com/dashenaichicha/p/12530712.html