Remove Duplicates from Sorted List II
来源:互联网 发布:win10录屏软件 编辑:程序博客网 时间:2024/05/16 10:41
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving onlydistinct 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
.
思路:注意:一定要做一个前指针,用来跳过所有相同的数,不然根据memory model,第一个相同的数的指针是不能delete自己的。指针指向会出问题,用cur 和curnext相比较来进行移动。
思路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 || head.next == null) return head; ListNode dump = new ListNode(0); dump.next = head; ListNode prehead = dump; ListNode pre = head; while(pre != null && pre.next!=null) { ListNode cur = pre.next; if(cur.val == pre.val) { while(cur!=null && cur.val == pre.val) { cur = cur.next; } prehead.next = cur; pre = cur; } else { prehead = pre; pre = pre.next; } } return dump.next; }}思路1:
/** * 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 || head.next == null) return head; ListNode dump = new ListNode(0); dump.next = head; ListNode pre = dump; while(pre.next!=null && pre.next.next!=null) { ListNode cur = pre.next; ListNode curnext = pre.next.next; if(cur.val != curnext.val) { pre = pre.next; } else { while(curnext!=null && cur.val == curnext.val){ curnext = curnext.next; } pre.next = curnext; } } return dump.next; }}
0 0
- LeetCode: Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- Remove duplicates from sorted list II
- Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- [LeetCode]Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- [leetcode]Remove Duplicates from Sorted List II
- Foxit Reader出现脚本错误提示的解决方法
- NGUI简易背包
- JS压缩工具---yuicompressor
- PHP实现同服务器多个二级域名共享 SESSION 数据
- 6-1通过原型继承创建一个新对象
- Remove Duplicates from Sorted List II
- 如何解决php中并发读写文件冲突的问题
- C++模板实战5: 迭代器与容器
- 实现jqGrid列表 css和js文件加载顺序详解
- vxl cannot build with share libs
- 三硬币问题
- Makefile介绍
- 获取Owner属性值的两种方式---Owner
- Java技术路线图