Prove safety Offer: delete the list of duplicate nodes (java version)

Title 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

Recursion

public class Solution {
    public ListNode deleteDuplication(ListNode pHead) {
        if (pHead == null || pHead.next == null) { // 只有0个或1个结点,则返回
            return pHead;
        }
        if (pHead.val == pHead.next.val) { // 当前结点是重复结点
            ListNode pNode = pHead.next;
            while (pNode != null && pNode.val == pHead.val) {
                // 跳过值与当前结点相同的全部结点,找到第一个与当前结点不同的结点
                pNode = pNode.next;
            }
            return deleteDuplication(pNode); // 从第一个与当前结点不同的结点开始递归
        } else { // 当前结点不是重复结点
            pHead.next = deleteDuplication(pHead.next); // 保留当前结点,从下一个结点开始递归
            // 表示将当前节点与下一节点不同,所以要将下一节点放入递归程序去参加下一轮的比较,这样就将pHead保留了下来。
            // 返回值给pHead.next表示deleteDuplication返回了一个无重复的节点,所以要让当前节点指向它。
            return pHead;
        }
    }
}

Creating a head pointer

public class Solution {
    public ListNode deleteDuplication(ListNode pHead) {
        if (pHead == null || pHead.next == null) { // 只有0个或1个结点,则返回
            return pHead;
        }
        ListNode head = new ListNode(-1);
        head.next = pHead;
        ListNode res = head;  // 指向确定不重复的结点
        ListNode cur = head.next; // 遍历的当前节点
        while(cur!=null){
            if(cur.next!=null && cur.val == cur.next.val){
                while(cur.next!=null && cur.val == cur.next.val){
                    cur = cur.next;
                }
                res.next = cur.next; // 找到下一个不重复的结点,链上res
                cur = cur.next;
            }else{
                res = res.next;
                cur = cur.next;
            }
        }
        return head.next;
    }
}

Guess you like

Origin blog.csdn.net/qq_43165002/article/details/90635716