题目:
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.
思路:
遍历一遍
Code:
public ListNode deleteDuplicates(ListNode head) {
if(head==null||head.next==null) return head;
ListNode pre=head,post=head.next;
while(pre.next!=null && post!=null){
if(pre.val==post.val){
pre.next=post.next;
if(post.next!=null) post=post.next;
}else{
pre=pre.next;
post=post.next;
}
}
return head;
}
Code2:
public ListNode deleteDuplicates(ListNode head) {
if(head==null) return head;
if(head.next==null) return head;
ListNode pre=head;
ListNode post=head;
while(post!=null){
post=post.next;
if(post==null){
pre.next=post;
break;
}
if(pre.val!=post.val){
pre.next=post;
pre=post;
}
}
return head;
}
备注:
Code1 比 Code2 效率高,原因未分析