0%

leetCode-83:Remove Duplicates from Sorted List

问题描述

给定一个有序链表,要求将链表中的重复节点删除。题目链接:**点我**

样例输入输出

输入:1->1->2

输出:1->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
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution
{
public ListNode deleteDuplicates(ListNode head)
{
if (head == null)
{
return head;
}

ListNode prev = head;
while (prev.next != null)
{
ListNode current = prev.next;
if (prev.val == current.val)
{
prev.next = current.next;
}
else
{
prev = prev.next;
}
}

return head;
}
}