Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
一个简单的排好序的链表,删除重复元素:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null||head.next==null)return head;
int lab=head.val;
ListNode next=head.next;
ListNode a=head;
while(next!=null)
{
if(lab==next.val)
{
a.next=next.next;
next=next.next;
}
else
{
lab=next.val;
a=a.next;
next=next.next;
}
}
return head;
}
}
那么如果这个链表没有排序呢?
我个人认为可以使用Set容器中的add和contains方法来判断