Leetcode82删除排序链表中重复元素2

代码:

为了找到结果的head 可以在head前加一个dummy dummy->head 再顺序去重

java 复制代码
/**
 * 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 head;
        // while(head.next!=null&&head.val==head.next.val){
        //     while(n1!=null&&n1.next!=null&&n1.val==n1.next.val){
        //         if(n1.next.next!=null){
        //             head=n1.next.next;
        //         }else{
        //             return null;
        //         }
        //         n1=n1.next;
        //     }
        // }
        if(head.next==null)return head;
        ListNode dummy = new ListNode(0,head);
        ListNode n1 = dummy;

        while(n1.next!=null&&n1.next.next!=null){
            ListNode n2 = n1.next;
            ListNode n3 = n1.next.next;
            if(n2.val==n3.val){
                while(n2.val==n3.val){
                    n2 = n3;
                    n3 = n3.next;
                    if(n2==null||n3==null){
                        n1.next=null;
                        break;
                    }else{
                        n1.next = n3;
                    }                    
                }
            }else{
                n1=n1.next;
            }
        }
        return dummy.next;
    }
}
相关推荐
m0_547486661 天前
《数据结构教程》全套 PPT课件2026
数据结构
tryxr1 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_31 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
All for pursuit.1 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.1 天前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
渡我白衣1 天前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.9922 天前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
无敌贵点大王2 天前
RTThread学习记录11——RT-Thread 设备模型吃透:UART/ADC/PWM/PIN 到底有什么区别?
c语言·stm32·学习·链表
淡海水2 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
Logic1012 天前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质