LeetCode83-删除排序链表中的重复元素

题目链接

英文链接:https://leetcode.com/problems/remove-duplicates-from-sorted-list/

中文链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/

题目详述

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

示例 1:

1
2
输入: 1->1->2
输出: 1->2

示例 2:

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

题目详解

链表简单题。

  • 比较当前结点与下一个结点的元素是否相同,若相同则改变当前结点的 next 指针指向,跳过重复的元素达到删除的目的。
  • 重复这个过程,直至到达链表末尾。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class LeetCode_00083 {

public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode cur = head;
while (cur.next != null) {
if (cur.val == cur.next.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
}
}