剑指offer--(18)删除链表中重复的结点--Java描述

写在前面:

    删除链表中重复的结点,我们需要考虑两种重复的情况:

(1)从head就开始重复 eg:{1,1,2,2,3}

(2)正常重复 eg:{1,2,2,3,3,5}

那么为了避免第一种情况出现,程序没有删除头结点,我们需要自己创建一个头结点:

		ListNode first = new ListNode(-1);// 新建一个头节点,避免,从head就开始重复

此外,我们还要用一个start结点,来记录重复结点出现之前的结点,比如,第二种情况中,start就记录结点1,最后再将结点5赋值给start.next。

代码实现:

public ListNode deleteDuplication(ListNode head) {
		ListNode first = new ListNode(-1);// 新建一个头节点,避免,从head就开始重复
		first.next = head;
		ListNode current = head;
		ListNode start = first; // 保存重复节点的前一个节点
		while (current != null && current.next != null) {
			if (current.val == current.next.val) {
				int value = current.val;
				while (current != null && current.val == value) {
					current = current.next;
				}
				start.next = current;
			} else {
				start = current;
				current = current.next;
			}
		}
		// 注意要返回first.next,避免从head就开始重复,而head被删除
		return first.next;
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值