LeetCode题解-83.删除排序链表中的重复元I

题目描述

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例1:

输入: 1->1->2

输出: 1->2

示例2:

输入: 1->1->2->3->3

输出: 1->2->3

解题思路

如果当前结点的值和下一个结点的值相等,则跳过下一个结点,直接连接下下个结点,代码表示就是

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

## 代码
```java
public static ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode current = head;
while (current.next != null) {
if (current.val == current.next.val) {
current.next = current.next.next;
} else {
current = current.next;
}
}
return head;
}

优化版

在讨论区里看到说上一种解法,在长链表的情况下,会产生很多野结点。改进版:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode current = head;
while (current.next != null) {
if (current.val == current.next.val) {
// 清除野结点
ListNode next = current.next;
current.next = next.next;
next.next = null;
} else {
current = current.next;
}
}
return head;
}