删除排序链表中的重复元素
2016-07-09 09:05
543 查看
题目
给定一个排序链表,删除所有重复的元素每个元素只留下一个。样例
给出 1->1->2->null,返回 1->2->null
给出 1->1->2->3->3->null,返回 1->2->3->null
解题
加一个头结点链表有序,找到不相等的时候,删除中间结点
两两比较是否相同进行删除
/** * Definition for ListNode * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { /** * @param ListNode head is the head of the linked list * @return: ListNode head of linked list */ public static ListNode deleteDuplicates(ListNode head) { // write your code here ListNode curHead = new ListNode(-1); // 定义头结点 curHead.next = head; while(head!=null){ if(head.next!=null && head.val == head.next.val){ // 遇到相同元素删除 head.next = head.next.next; }else head = head.next; } return curHead.next; } }
删除多个的方式
只需修改上面的if语句
/** * Definition for ListNode * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { /** * @param ListNode head is the head of the linked list * @return: ListNode head of linked list */ public static ListNode deleteDuplicates(ListNode head) { // write your code here ListNode curHead = new ListNode(-1); // 定义头结点 curHead.next = head; while(head!=null){ while(head.next!=null && head.val == head.next.val){ // 遇到相同元素删除 head.next = head.next.next; } head = head.next; } return curHead.next; } }
相关文章推荐
- Java千百问_08JDK详解(017)_Javadoc是什么
- 李洪强iOS开发之【零基础学习iOS开发【01-前言】03-前景和难易度分析
- MIF in Android 5.0
- cracking the code interview——c++实现
- Codeforces 689E Mike and Geometry Problem(离散化+懒标记)
- 客服对于Kindle电子书的退货、倒闭、VR等问题的回答
- setBackgroundDrawable和setBackgroundColor的用法
- websevice接口调用
- 安卓中实现欢迎界面延时进入主界面代码
- Linux安装包选择
- decimal(小数) module
- SELECT TOP 1 * FROM是什么意思
- 获取窗口的句柄方法总结
- 玩无限消乐的设计示例(基础篇)DataGridView控件添加拖放事件方法和委托
- 关于TCP Zero Window Update感知的非常棒的优化
- 【树链剖分(区间线段树)】BZOJ4196-[NOI2015]软件包管理
- PHP面向对象技术(全面讲解)
- hdu 2124 Repair the Wall
- 虚函数表
- centos lnmp环境配置ssl证书支持https访问