添加py和js,添加注释,去除去除多余代码

pull/33/head
jaredliw 2021-07-15 15:54:27 +08:00
parent 8d3681f0e3
commit 813cfddd0b
1 changed files with 79 additions and 18 deletions

View File

@ -6,7 +6,7 @@
#### [82. II](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/)
****
@ -35,7 +35,7 @@
![2](https://cdn.jsdelivr.net/gh/tan45du/photobed@master/photo/删除重复节点2.3btmii5cgxa0.gif)
@ -46,20 +46,22 @@ Java Code:
```java
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null||head.next==null){
return head;
}
//侦察兵指针
ListNode pre = head;
ListNode low = new ListNode(0);
low.next = pre;
ListNode ret = new ListNode(-1);
ret = low;
//创建虚拟头节点接上head
ListNode dummy = new ListNode(-1);
dummy.next = pre;
//跟随的指针
ListNode low = dummy;
while(pre != null && pre.next != null) {
if (pre.val == pre.next.val) {
//移动侦察兵指针直到找到与上一个不相同的元素
while (pre != null && pre.next != null && pre.val == pre.next.val) {
pre = pre.next;
}
//while循环后pre停留在最后一个重复的节点上
pre = pre.next;
//连上新节点
low.next = pre;
}
else{
@ -67,7 +69,7 @@ class Solution {
low = low.next;
}
}
return ret.next;
return dummy.next;//注意这里传回的不是head而是虚拟节点的下一个节点head有可能已经换了
}
}
```
@ -78,20 +80,22 @@ C++ Code:
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head == nullptr || head->next == nullptr){
return head;
}
//侦察兵指针
ListNode * pre = head;
ListNode * low = new ListNode(0);
low->next = pre;
ListNode * ret = new ListNode(-1);
ret = low;
//创建虚拟头节点接上head
ListNode * dummy = new ListNode(-1 head);
dummy->next = pre;
//跟随的指针
ListNode * low = dummy;
while(pre != nullptr && pre->next != nullptr) {
if (pre->val == pre->next->val) {
//移动侦察兵指针直到找到与上一个不相同的元素
while (pre != nullptr && pre->next != nullptr && pre->val == pre->next->val) {
pre = pre->next;
}
//while循环后pre停留在最后一个重复的节点上
pre = pre->next;
//连上新节点
low->next = pre;
}
else{
@ -99,8 +103,65 @@ public:
low = low->next;
}
}
return ret->next;
return dummy->next;//注意这里传回的不是head而是虚拟节点的下一个节点head有可能已经换了
}
};
```
JS Code:
```javascript
var deleteDuplicates = function(head) {
//侦察兵指针
let pre = head;
//创建虚拟头节点接上head
let dummy = new ListNode(-1);
dummy.next = pre;
//跟随的指针
let low = dummy;
while(pre != null && pre.next != null) {
if (pre.val == pre.next.val) {
//移动侦察兵指针直到找到与上一个不相同的元素
while (pre != null && pre.next != null && pre.val === pre.next.val) {
pre = pre.next;
}
//while循环后pre停留在最后一个重复的节点上
pre = pre.next;
//连上新节点
low.next = pre;
}
else{
pre = pre.next;
low = low.next;
}
}
return dummy.next;//注意这里传回的不是head而是虚拟节点的下一个节点head有可能已经换了
};
```
Python Code:
```py
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
#
pre = head
# head
dummy = ListNode(-1, head)
#
low = dummy
while pre is not None and pre.next is not None:
if pre.val == pre.next.val:
#
while pre is not None and pre.next is not None and pre.val == pre.next.val:
pre = pre.next
# whilepre
pre = pre.next
#
low.next = pre
else:
pre = pre.next
low = low.next
return low.next # headhead
```