Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
题目
删除链表中重复的元素,和203. Remove Linked List Elements的区别在于,这回去掉重复的后,保留一个,不全删除。最后使得链表元素都唯一
思路
首先链表是有序的,这就大大降低了操作难度,因为重复元素都是相邻的,只要判断相邻元素是否相等即可。
代码
public ListNode deleteDuplicates(ListNode head) {
ListNode q=head;
while (q!=null&&q.next!=null) {
if (q.val==q.next.val) {
q.next=q.next.next;
}else {
q=q.next;
}
}
return head;
}