leetcode83/82. 删除排序链表中的重复元素(保留或者全删除)

1)每次重复的只要一次。

如果遇见相对了的直接跳过,跳到不等的地方。

/**
 * 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){
                return null;
            }
            ListNode cur = head;
            while(cur.next != null){
                if(cur.next.val == cur.val){
                    cur.next = cur.next.next;
                }else{
                cur = cur.next;
                }
            }
            return head;
    }
}

 2)重复的全删除

 

找到相同节点的最后一个节点x,然后pre.next = x.next。就相当于把重复的元素全部删除了。

/**
 * 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){
            return null;
        }
        //怕第一个头节点就是重复节点,所以弄一个辅助节点排除特殊情况。返回的是helpNode.next就行。
        ListNode helpNode = new ListNode(Integer.MAX_VALUE);
        helpNode.next = head;
        ListNode pre = helpNode;
        ListNode cur = helpNode;
        while(cur!=null){
             while(cur.next != null && cur.next.val == cur.val){
                 cur = cur.next;
             }//来到相同节点的最后一个相同节点。
                cur = cur.next;
                //此时的cur来到的位置是相同节点的下一个,也就是当前节点和前面的重复节点不一样,此时也需要判断一个当前节点和下一个节点是不是也是相同节点比如1->2->2->3->3,此时的cur就是第一个3
                if(cur!=null && cur.next != null && cur.val == cur.next.val){
                    continue;//就是上面的一种情况,重复一遍,遇见相同的就重复。找到不同的。
                }
                //如果上面的3只有一次,那么就把pre.next的指针指向它
                pre.next = cur;
                pre = pre.next;
        }
        return helpNode.next;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

失忆机器

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值