【链表】剑指Offer: 删除链表中重复的结点

【在线编程】 删除链表中重复的结点

【问题描述】

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

【解题思路 & Java实现】

首先看下这个题目:删除有序链表中重复的结点,重复的结点只保留一个
思路:p指针是工作指针,post指针指向p的下一个结点,当p.val == post.val时,post一直向后遍历,直到找到与p值不同为止。
在这里插入图片描述

 /*
 public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
    public static ListNode deleteDuplication(ListNode pHead) {
        if (pHead == null || pHead.next == null) {
            return pHead;
        }

        ListNode p = pHead;
        ListNode post = pHead.next;

        while (post != null) {
            if (p.val == post.val) {
                while (post != null && p.val == post.val) {
                    post = post.next;
                }

                p.next = post;

            } else {
                p = post;
                post = post.next;
            }
        }

        return pHead;
    }
}

方本题思路:在上题的基础上,加个pre指针,pre指针指向p的前一个结点,在删除相同结点的时候,让pre.next = post.然后向后移动p和post结点。
在这里插入图片描述

/*
 public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
    public static ListNode deleteDuplication(ListNode pHead) {
        if (pHead == null || pHead.next == null) {
            return pHead;
        }

        ListNode head = new ListNode(-1);
        head.next = pHead;

        ListNode pre = head; //pre指向不同的结点
        ListNode p = pHead;
        ListNode post = pHead.next;

        while (post != null) {
            if (p.val == post.val) {
                while (post != null && p.val == post.val) {
                    post = post.next;
                }
                
                pre.next = post;
                
                //重置一下p和post
                if (post != null) {
                    p = post;
                    post = post.next;
                }

            } else {
                pre = p;
                p = post;
                post = post.next;
            }
        }

        return head.next;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值