Given a sorted linked list, delete all duplicates such this each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
Subscribe to see which companies asked this question
This is a list without a head node, we just have to delete the duplicate (because the list is well-ordered, we just need to determine whether the value of the latter is equal to the former, if equal to delete)
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Deleteduplicates (listnode*head) { if(!head)returnHead; ListNode*pre = head, *current = pre->Next; while(current) {if(Current->val = = pre->val) {Pre->next = current->Next; Free(current); Current= pre->Next; } Else{ Current= current->Next; Pre= pre->Next; } } returnHead; }};
Leetcode 83. Remove Duplicates from Sorted List