Given a sorted linked list, delete all duplicates such that each element appears only once.
For example:
- Given 1->1->2, return 1->2.
- Given 1->1->2->3->3, return 1->2->3.
The following is my code:
struct ListNode {
int data;
ListNode *next;
ListNode(int x) : data(x), next(NULL) {}
};
ListNode *getNextElement(ListNode *head){
while ((head != NULL) && (head->next != NULL)
&& (head->data == head->next->data)){
head = head->next;
}
return head->next;
}
ListNode *deleteDuplicates(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode *cur = head;
ListNode *next = NULL;
while (cur != NULL){
next = getNextElement(cur);
cur->next = next;
cur = next;
}
return head;
}