原题:
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2 Output: 1->2Example 2:
Input: 1->1->2->3->3 Output: 1->2->3
与之前的做过的https://blog.csdn.net/cyr429/article/details/89489933中的题相似,只不过那个是使用数组而这个是链表存储,原理相同,就不赘述了,结果如下:
Success
Runtime: 8 ms, faster than 99.88% of C++ online submissions for Remove Duplicates from Sorted List.
Memory Usage: 9.3 MB, less than 39.48% of C++ online submissions for Remove Duplicates from Sorted List.
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head==NULL){return head;}
ListNode *front,*rear;
front=head;rear=head;
while(front!=NULL){
if(front->val!=rear->val){
rear=rear->next;
rear->val=front->val;
}
front=front->next;
}
rear->next=NULL;
return head;
}
};