博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode Remove Duplicates from Sorted List II
阅读量:4647 次
发布时间:2019-06-09

本文共 1442 字,大约阅读时间需要 4 分钟。

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.

 

每个节点与前驱节点还有后继相比较,若有一个相等,就跳过这个节点。

 

1 /** 2  * Definition for singly-linked list. 3  * public class ListNode { 4  *     int val; 5  *     ListNode next; 6  *     ListNode(int x) { 7  *         val = x; 8  *         next = null; 9  *     }10  * }11  */12 public class Solution {13     public ListNode deleteDuplicates(ListNode head) {14         if (head == null || head.next == null) {15             return head;16         }17         ListNode start = new ListNode(head.val - 1);18         ListNode temp=start;19         ListNode curr=head;20         int prev=start.val;21         int next=head.next.val;22         while (curr.next != null) {23             if (curr.val != prev && curr.val != curr.next.val) {24                 prev = curr.val;25                 temp.next = curr;26                 temp=temp.next;27                 curr = curr.next;28             } else {29                 prev=curr.val;30                 curr=curr.next;31                 if(curr.next!=null) next=curr.next.val;32             }33         }34         if (curr.val != prev) {35             temp.next = curr;36         }else temp.next=null;37         return start.next;38         39     }40 }

 

转载于:https://www.cnblogs.com/birdhack/p/4209595.html

你可能感兴趣的文章
IDEA操作git
查看>>
windows 下安装elasticsearch
查看>>
C语言学习12:带参数的main函数,无指定的函数形参,调用库函数处理无指定的函数形参,...
查看>>
禁止某程序联网
查看>>
[LOJ6191][CodeM]配对游戏(概率期望DP)
查看>>
mysql中utf8和utf8mb4区别
查看>>
谈谈源码管理那点事儿(一)——源码管理十诫(转)
查看>>
拒绝switch,程序加速之函数指针数组
查看>>
[你必须知道的.NET]第二十五回:认识元数据和IL(中)
查看>>
.NET中的三种Timer的区别和用法
查看>>
python第三方包安装方法(两种方法)
查看>>
MySQL 索引知识整理(创建高性能的索引)
查看>>
C++ 头文件
查看>>
ZOJ 1008 Gnome Tetravex(DFS)
查看>>
Mysql基础知识:操作数据库
查看>>
mysql 数据库远程访问设置方法
查看>>
Far manager界面混乱问题解决
查看>>
java读取xml文件
查看>>
Go数组和切片定义和初始化
查看>>
用javascript将数据导入Excel
查看>>