(Java refers to offer) Delete duplicate nodes in the linked list

1. Question analysis

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

The key to this question is to consider the possibility that the first node and the second node will be duplicated, so you need to add a head node first, and subsequent judgments can add the pre pointer to indicate the precursor, and the last pointer to indicate that the working pointer is responsible for the subsequent search

Second, the code

public class Test_14 {
    
    
    public static void main(String[] args) {
    
    
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(1);
        ListNode node3 = new ListNode(1);
        ListNode node4 = new ListNode(1);
        ListNode node5 = new ListNode(1);
        ListNode node6 = new ListNode(1);
        ListNode node7 = new ListNode(1);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        node6.next = node7;

        ListNode result = deleteDuplication(node1);
        while (result != null) {
    
    
            System.out.println(result.val);
            result = result.next;
        }
    }

    private static ListNode deleteDuplication(ListNode pHead) {
    
    
        if (pHead == null || pHead.next == null) {
    
    
            return pHead;
        }
        //首先添加一个头结点,防止出现第一个和第二个结点就相同的情况
        ListNode head = new ListNode(0);
        head.next = pHead;
        //pre 指向当前确定不重复的结点,last 表示工作结点,负责往后搜索
        ListNode pre = head;
        ListNode last = pHead;
        while (last != null) {
    
    
            ListNode temp = last.next;
            if (temp != null && last.val == temp.val) {
    
    
                while (temp != null && last.val == temp.val) {
    
    
                    temp = temp.next;
                }
                pre.next = temp;
                last = temp;
            } else {
    
    
                pre = pre.next;
                last = temp;
            }
        }
        return head.next;
    }
}

Three, summary

For the deletion of the linked list, two pointers are generally used, one precursor and one working pointer

Guess you like

Origin blog.csdn.net/nanhuaibeian/article/details/108592220