Remove Duplicates from Sorted List II
来源:互联网 发布:浙江师范行知学院宿舍 编辑:程序博客网 时间:2024/05/20 13:16
Fair Remove Duplicates from Sorted List IIMy Submissions
28%
Accepted
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving onlydistinct numbers from the original list.
Example
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
1. use dummy node. Because the head of the original node might be changed.
2. every iteration we compare head.next.val with head.next.next.val. Save head.next.val if the the two adjacent nodes are equal. And use a while loop to delete all the nodes with the same value. The deletion starts from head.next.
</pre><pre name="code" class="java">
</pre><p></p><p><pre name="code" class="java">/** * 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 the linked list */ public static ListNode deleteDuplicates(ListNode head) { if (head == null || head.next == null) { return head; } ListNode dummy = new ListNode(0); dummy.next = head; head = dummy; while (head.next != null && head.next.next != null) { if (head.next.val == head.next.next.val) { int val = head.next.val; while (head.next != null && head.next.val == val) { head.next = head.next.next; } } else { head = head.next; } } return dummy.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
- UIApplication解析
- Mathematical aspects of finite element I (有限元的数学概念)
- 【编程之美】微软技面心得
- 有序矩阵中查找第k小的元素 Kth smallest element in a row-wise and column-wise sorted 2D array
- [leetcode] Decode Ways
- Remove Duplicates from Sorted List II
- Reverse Linked List
- appcompat_v7 与 actionbarsherlock 冲突解决/移除项目中的appcompat_v7
- python 函数小结
- R apply, lapply, sapply, mapply, tapply functions
- OpenWrt的差异化特性介绍
- Reverse Linked List II
- 接口设备发包
- js表中验证常用正则表达式