題目:刪除排序鏈表中的重複元素。
給定一個排序鏈表,刪除所有重複的元素,使得每個元素只出現一次。
2.解法 1ms
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode cnode=new ListNode(0); //創建一個含頭節點的鏈表
ListNode p=cnode;
if(head==null){
return null;
}
while(head!=null){
if(head.next==null ){
p.next=head;
} else if(head.val!=head.next.val){
p.next=head;
p=p.next;
}
head=head.next;
}
return cnode.next;
}
}