Sword refers to Offer-53-the entry node of the ring in the linked list

Title description

In a sorted linked list, there are duplicate nodes. Please delete the duplicate nodes in the linked list. The duplicate nodes are not retained, and the head pointer of the linked list is returned. For example, the linked list 1->2->3->3->4->4->5 is processed as 1->2->5

Idea analysis

The difficulty in solving this problem lies in how to delete the node pointed to by the pointer, while ensuring that the pointer can continue to be used instead of becoming null because of deletion.
Here, a new linked list containing the first node is used. Then connect the pHead. Achieve the effect of delaying one to delete duplicate nodes.

  • First, set two pointers as a fast pointer and the other as a slow pointer. When the fast pointer encounters a repetition, it advances quickly by itself until it reaches a value that is not a repetition. (The linked list is ordered, so there is no need to consider the recurrence later.) If the fast pointer does not encounter a repetition, it moves one step, and the slow pointer also moves one step at this time. At this time, the slow pointer is a position behind the fast pointer.
    Such as 1,2,3,3,4,4,5. For example, when the fast pointer points to 2, the slow pointer points to 1, and when the fast pointer points to 3, the slow pointer points to 2. At the same time, the fast pointer detects that fast.next is a duplicate, so it continues to the back. Directly to fast.val != fast.next.val. At this time, adjust slow.next and directly point it to fast. to achieve the effect of deletion.

Code

/*
 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 pHead;
        ListNode current = new ListNode(-1);
        current.next = pHead;
        ListNode fast = current.next;
        ListNode slow = current;
        while(fast!=null){
    
    
            if(fast.next!=null && fast.next.val == fast.val){
    
    
                //如果fast指针和它的next值一样,说明是重复值,就将其一直往下遍历
                while(fast.next!=null&&fast.next.val == fast.val){
    
    
                    //移动fast到不为重复值出
                    fast = fast.next;
                }
                //如果fast到了不为重复值的地方就将其赋给slow进行,slow指针的调整,达到删除重复节点的效果
                //值的注意的是此时的cur.next才是第一个重复的,因此需要再移动一步
                fast = fast.next;
                slow.next = fast;
            }else{
    
    
                //如果fast此时的值和fast.next的值此时不相同,就将其都移动一步
                slow = fast;
                fast = fast.next;
            }
        }
        return current.next;
    }
}

Guess you like

Origin blog.csdn.net/H1517043456/article/details/107513125