Leetcode 82. Remove Duplicates from Sorted List II

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

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

Subscribe to see which companies asked this question

思路:
(为了使头结点的操作方便,创建一个伪头结点指向头结点,使得头结点的操作没有特殊性)
创建两个指针第一个指针指向要判断序列结点,第二个指针来判断之后的结点是不是与这个结点之前的数值一样
1)如果不同,第一个指针就可以向后移一个步数,第二个指针重新指向第一个指针后面的,然后重复上述操作
2)如果相同,则第二个指针一直后移,直到与第一个之后后面的数值不同,然后重复上述操作

具体代码实现:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null){
            return null;
        }
        if(head.next == null){
            return head;
        }
        ListNode phead = new ListNode(0);
        phead.next = head;
        ListNode p = phead;
        ListNode end = p.next;

        while(p.next != null){
            int temp = p.next.val;
            if(end.next == null){
                break;
            }
            if(end.next.val != temp){
                p = p.next;
                end = p.next;
            }else{
                while(end.next!=null && end.next.val == temp){
                    end = end.next;
                }
                p.next = end.next;
                end = p.next;
            }
        }
        return phead.next;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值