《剑指 Offer》——56、删除链表中重复的结点

    技术2022-07-10  103

    1. 本题知识点

    链表

    2. 题目描述

    在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表 1->2->3->3->4->4->5 处理后为 1->2->5

    3. 解题思路

    直接看代码吧,由于使用了递归,难以解释清楚。

    4.代码

    public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } public class Solution { /** * 删除链表中重复的结点 * * @param pHead * @return */ public ListNode deleteDuplication(ListNode pHead) { // 如果当前结点为空,或当前结点没有后继结点,则直接返回当前结点 if (pHead == null || pHead.next == null) { return pHead; } // next 为后继结点 ListNode next = pHead.next; // 如果当前结点不等于后继结点 if (pHead.val != next.val) { pHead.next = deleteDuplication(pHead.next); return pHead; } // 如果当前结点等于后继结点 else { while (next != null && pHead.val == next.val) { next = next.next; } return deleteDuplication(next); } } }
    Processed: 0.014, SQL: 9