剑指Offer:删除链表中重复的结点(java版)

题目描述

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

递归

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;
        }
    }
}

创建一个头指针

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;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43165002/article/details/90635716