83.删除排序链表中的重复元素
对于重复的只取最后一个ListNode即可,通过递归依次去重
1
/**
2
* Definition for singly-linked list.
3
* public class ListNode {
4
* int val;
5
* ListNode next;
6
* ListNode(int x) { val = x; }
7
* }
8
*/
9
class Solution {
10
public ListNode deleteDuplicates(ListNode head) {
11
if(head == null){
12
return null; //终止递归
13
}
14
int val = head.val;
15
while(head.next != null && val == head.next.val){
16
head = head.next;
17
}
18
head.next = deleteDuplicates(head.next);
19
return head;
20
}
21
}
Copied!
另外一种解法,取重复的第一个为current,然后如果是重复的就跳过。
1
//1->1->2->3->3
2
public ListNode deleteDuplicates(ListNode head) {
3
ListNode current = head;
4
while (current != null && current.next != null) {
5
if (current.next.val == current.val) {
6
//跳过
7
current.next = current.next.next;
8
} else {
9
current = current.next;
10
}
11
}
12
return head;
13
}
Copied!
最近更新 1yr ago
复制链接