|
29 | 29 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
30 | 30 |
|
31 | 31 | ```python
|
32 |
| - |
| 32 | +# Definition for singly-linked list. |
| 33 | +# class ListNode: |
| 34 | +# def __init__(self, val=0, next=None): |
| 35 | +# self.val = val |
| 36 | +# self.next = next |
| 37 | +class Solution: |
| 38 | + def deleteDuplicates(self, head: ListNode) -> ListNode: |
| 39 | + dummy = ListNode(-1, head) |
| 40 | + cur = dummy |
| 41 | + while cur.next and cur.next.next: |
| 42 | + if cur.next.val == cur.next.next.val: |
| 43 | + val = cur.next.val |
| 44 | + while cur.next and cur.next.val == val: |
| 45 | + cur.next = cur.next.next |
| 46 | + else: |
| 47 | + cur = cur.next |
| 48 | + return dummy.next |
33 | 49 | ```
|
34 | 50 |
|
35 | 51 | ### **Java**
|
36 | 52 |
|
37 | 53 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
38 | 54 |
|
39 | 55 | ```java
|
| 56 | +/** |
| 57 | + * Definition for singly-linked list. |
| 58 | + * public class ListNode { |
| 59 | + * int val; |
| 60 | + * ListNode next; |
| 61 | + * ListNode() {} |
| 62 | + * ListNode(int val) { this.val = val; } |
| 63 | + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } |
| 64 | + * } |
| 65 | + */ |
| 66 | +class Solution { |
| 67 | + public ListNode deleteDuplicates(ListNode head) { |
| 68 | + ListNode dummy = new ListNode(-1, head); |
| 69 | + ListNode cur = dummy; |
| 70 | + while (cur.next != null && cur.next.next != null) { |
| 71 | + if (cur.next.val == cur.next.next.val) { |
| 72 | + int val = cur.next.val; |
| 73 | + while (cur.next != null && cur.next.val == val) { |
| 74 | + cur.next = cur.next.next; |
| 75 | + } |
| 76 | + } else { |
| 77 | + cur = cur.next; |
| 78 | + } |
| 79 | + } |
| 80 | + return dummy.next; |
| 81 | + } |
| 82 | +} |
| 83 | +``` |
40 | 84 |
|
| 85 | +### **C++** |
| 86 | + |
| 87 | +```cpp |
| 88 | +/** |
| 89 | + * Definition for singly-linked list. |
| 90 | + * struct ListNode { |
| 91 | + * int val; |
| 92 | + * ListNode *next; |
| 93 | + * ListNode() : val(0), next(nullptr) {} |
| 94 | + * ListNode(int x) : val(x), next(nullptr) {} |
| 95 | + * ListNode(int x, ListNode *next) : val(x), next(next) {} |
| 96 | + * }; |
| 97 | + */ |
| 98 | +class Solution { |
| 99 | +public: |
| 100 | + ListNode* deleteDuplicates(ListNode* head) { |
| 101 | + ListNode* dummy = new ListNode(-1, head); |
| 102 | + ListNode* cur = dummy; |
| 103 | + while (cur->next != nullptr && cur->next->next != nullptr) { |
| 104 | + if (cur->next->val == cur->next->next->val) { |
| 105 | + int val = cur->next->val; |
| 106 | + while (cur->next != nullptr && cur->next->val == val) { |
| 107 | + cur->next = cur->next->next; |
| 108 | + } |
| 109 | + } else { |
| 110 | + cur = cur->next; |
| 111 | + } |
| 112 | + } |
| 113 | + return dummy->next; |
| 114 | + } |
| 115 | +}; |
41 | 116 | ```
|
42 | 117 |
|
43 | 118 | ### **...**
|
|
0 commit comments