LeetCode 82.Remove Duplicates from Sorted List II Linked List/Medium


1.Description

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Return the linked list sorted as well.


2.Example

Input: 1->2->3->3->4->4->5
Output: 1->2->5

3.Solution

1.双指针一

思路类似于:
LeetCode 83.Remove Duplicates from Sorted List(从已排序链表中除去重复) Easy/Linked List

不过有几点区别:

1.因为删去的操作涉及到头结点,所以需要创建出一个哑结点,以此来对头结点是否满足要求进行判断。
2.这里不能跟83题一样,需要使用嵌套的循环来将所有重复的都跳过。
3.返回的是哑结点的下一位。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode p, dummy = new ListNode(0);
        p = dummy;
        dummy.next = head;
        while (head != null && head.next != null) {
            if (head.val == head.next.val) {
                while (head.next != null && head.val == head.next.val) {
                    head = head.next;
                }
                head = head.next;
                p.next = head;
            } else {
                head = head.next;
                p = p.next;
            }
        }
        return dummy.next;
    }
}

2.双指针二

这里是力扣的题解。
b指针比a指针快,用a.next.val的值来跟b.next.val的值比较从而判断是否还有重复的。

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head==null || head.next==null) {
            return head;
        }
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode a = dummy;
        ListNode b = head;
        while(b!=null && b.next!=null) {
            //初始化的时a指向的是哑结点,所以比较逻辑应该是a的下一个节点和b的下一个节点
            if(a.next.val!=b.next.val) {
                a = a.next;
                b = b.next;
            }
            else {
                //如果a、b指向的节点值相等,就不断移动b,直到a、b指向的值不相等 
                while(b!=null && b.next!=null && a.next.val==b.next.val) {
                    b = b.next;
                }
                a.next = b.next;
                b = b.next;
            }
        }
        return dummy.next;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值