6
头图

delete duplicate nodes in linked list

Topic 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 pointer to the head of the linked list is returned. For example, the linked list 1->2->3->3->4->4->5 is processed as 1->2->5.

topic link : delete duplicate nodes in the linked list

code

/**
 * 标题:删除链表中重复的结点
 * 题目描述
 * 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
 * 题目链接:
 * https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef?tpId=13&&tqId=11209&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
 */
public class Jz56 {

    public ListNode deleteDuplication(ListNode pHead) {
        if (pHead == null || pHead.next == null) {
            return pHead;
        }
        ListNode next = pHead.next;
        if (pHead.val == next.val) {
            while (next != null && pHead.val == next.val) {
                next = next.next;
            }
            return deleteDuplication(next);
        } else {
            pHead.next = deleteDuplication(pHead.next);
            return pHead;
        }
    }

    public static void main(String[] args) {
        ListNode pHead = new ListNode(1);
        pHead.next = new ListNode(1);
        pHead.next.next = new ListNode(1);
        pHead.next.next.next = new ListNode(1);
        pHead.next.next.next.next = new ListNode(1);
        pHead.next.next.next.next.next = new ListNode(1);
        pHead.next.next.next.next.next.next = new ListNode(1);

        System.out.println("删除重复节点前的链表");
        ListNode cur = pHead;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();

        System.out.println("删除重复节点后的链表");
        Jz56 jz56 = new Jz56();
        ListNode result = jz56.deleteDuplication(pHead);
        cur = result;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
    }
}
[Daily Message] Every morning full of hope, tell yourself to work hard in order to meet a better self.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!