83. Remove Duplicates from Sorted List Easy

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

1
2
Input: 1->1->2
Output: 1->2

Example 2:

1
2
Input: 1->1->2->3->3
Output: 1->2->3

思路:

思路一:双指针

由于都是已经排好序的链表,相同的数都在一起,只要使用双指针:一个指向出现的第一个数,一个一直遍历到这个数结束即可

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) return head;
ListNode slow = head;
ListNode fast = head.next;
while (fast != null) {
if (slow.val == fast.val) {
fast = fast.next;
slow.next = fast;
}
else {
slow = slow.next;
fast = fast.next;
}
}
return head;
}

评论