83. Remove Duplicates from Sorted List

时间:2022-12-18 23:39:18

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; ListNode heads=head;
ListNode p=head.next;
while(p!=null)
{
if(p.val==heads.val)
{
p=p.next;
heads.next=p;
}
else
heads=heads.next;
}
return head;
}
}