题目:
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
.
因为是有序链表,所以去重只需要比较新来的节点和前面一个节点是否相同,如果相同直接删除就可以了。思考一个问题,因为在链表不为空的情况下,第一个节点是不可能会被删除的,所以我们不需要向前面那样,在第一个节点之前创建一个节点,我们直接从第二个节点开始比较。
代码:
public static ListNode deleteDuplicates(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode pre=head;
ListNode cur=head.next;
while(cur!=null)
{
if(cur.val==pre.val)
{
pre.next=cur.next;//删除重复的节点
}
else {
pre=pre.next;
}
cur=cur.next;
}
return head;
}