JZ56-删除链表中重复的结点
删除链表中重复的结点
https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey
class Solution { 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; } } } class Solution2 { public ListNode deleteDuplication(ListNode pHead) { if (pHead == null || pHead.next == null) { return pHead; } ListNode Head = new ListNode(0); //哨兵 Head.next = pHead; ListNode pre = Head; //先定义一个前指针,用于正确构建 ListNode next = Head.next; while (next != null) { if (next.next != null && next.val == next.next.val) { //如果有相等的 while (next.next != null && next.val == next.next.val) { //找到最后一个相等的 next = next.next; } pre.next = next.next; //前一个直接指向不相等的第一个 next = next.next; } else { pre = pre.next; next = next.next; } } return Head.next; } }