剑指offer之删除链表中重复的结点(Java实现)

版权声明:转载请联系 :[email protected] https://blog.csdn.net/weixin_40928253/article/details/85253736

删除链表中重复的结点

NowCoder

题目描述:

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

###解题思路:

解法一:递归

public class Solution{
    public  ListNode deleteDuplication(ListNode pHead){
        if (pHead == null || pHead.next == null )  
            return pHead;
        //处理重复结点
        if (pHead.val == pHead.next.val){
            ListNode cur = pHead.next;
            while (cur != null && cur.val == pHead.val){
                cur = cur.next;
            }
            return deleteDuplication(cur);
        }
        //该结点不重复,递归到下一个结点
        pHead.next = deleteDuplication(pHead.next);
        return pHead;
    }
}

解法二:非递归 三指针

public class Solution {
    public ListNode deleteDuplication(ListNode pHead){
        //设置一个头结点,让从一开始就节点重复更好操作
        ListNode first = new ListNode(-1);
        first.next = pHead;
        ListNode p = pHead;
        ListNode last = first;//用户删除重复节点的节点
        while (p != null && p.next != null) {
            if (p.val == p.next.val) {
                int val = p.val;
                while (p!= null&&p.val == val){
                    p = p.next;
                }
                last.next = p;//删除重复节点
            } else {
                last = p;
                p = p.next;
            }
        }
        return first.next;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40928253/article/details/85253736