58. Delete duplicate node 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

Analysis of ideas:

  Two ideas:

  The first method does not use a recursive, allowed to set a pointer pointing to the first node in the list, we start traversing head node, to delete the duplicate node values ​​is determined whether the current node and the next node values ​​are equal, if the downward traversal until it encounters the first node is not equal, the new head of the list from the start point, then the above operation is repeated to find the next node will not be repeated.

  The second method is to use recursion, the same ideas and above.

Code:

method one:

/*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)
            return null;
        if(pHead.next==null)
            return pHead;
        ListNode first=new ListNode(-1);
        first.next=pHead;
        ListNode last=first;
        ListNode pNode=pHead;
        while(pNode!=null&&pNode.next!=null){
            if(pNode.val==pNode.next.val){
                int val=pNode.val;
                while(pNode!=null&&pNode.val==val){  //切记在链表中循环遍历一定要判断当前节点是否为空。
                    pNode=pNode.next;
                }
                last.next=pNode;   
            }else{
                last=pNode;
                pNode=pNode.next;
            }
        }
        return first.next;
    }
}

Method Two:

/*
 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)
            return null;
        if(pHead.next==null)
            return pHead;
        if(pHead.val==pHead.next.val){
            ListNode pNode=pHead;
            int val=pNode.val;
            while(pNode!=null&&val==pNode.val){
                pNode=pNode.next;
            }
            return deleteDuplication(pNode);   //找到第一个不重复的点开始递归。
             
        }else{
            pHead.next=deleteDuplication(pHead.next); //如果当前节点不是重复的保存下来,从下一个节点开始递归。
            return pHead;
        }
        
}
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/10961217.html