Skip to content

Commit 75f89c6

Browse files
committed
0082. Remove Duplicates from Sorted List II
1 parent daa159e commit 75f89c6

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
### [82\. Remove Duplicates from Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)
2+
3+
Difficulty: **Medium**
4+
5+
6+
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only _distinct_ numbers from the original list.
7+
8+
**Example 1:**
9+
10+
```
11+
Input: 1->2->3->3->4->4->5
12+
Output: 1->2->5
13+
```
14+
15+
**Example 2:**
16+
17+
```
18+
Input: 1->1->1->2->3
19+
Output: 2->3
20+
```
21+
22+
23+
#### Solution
24+
25+
Language: **Java**
26+
27+
```java
28+
/**
29+
* Definition for singly-linked list.
30+
* public class ListNode {
31+
* int val;
32+
* ListNode next;
33+
* ListNode(int x) { val = x; }
34+
* }
35+
*/
36+
class Solution {
37+
   public ListNode deleteDuplicates(ListNode head) {
38+
       if (head == null) {
39+
           return null;
40+
      }
41+
       ListNode fakeHead = new ListNode(0);
42+
       fakeHead.next = head;
43+
       ListNode pre = fakeHead;
44+
       ListNode curr = head;
45+
       while (curr != null) {
46+
           while (curr.next != null && curr.val == curr.next.val) {
47+
               curr = curr.next;
48+
          }
49+
           if (pre.next == curr) { // 说明该次循环没有重复元素
50+
               pre = pre.next;
51+
          } else {
52+
               pre.next = curr.next;
53+
          }
54+
           curr = curr.next;
55+
56+
      }
57+
       return fakeHead.next;
58+
  }
59+
}
60+
```
61+
![pic](https://raw.githubusercontent.com/PicGoBed/PicBed/master/2019-07-29-bjF2FD.jpg)

0 commit comments

Comments
 (0)