The topics are as follows:
Given a sorted linked list, delete all duplicates such which each element is appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
Topic Analysis:
The subject is given a linked list, the linked list filter weight, so that each number appears only once.
And the previous topic Leetcode () Remove duplicates from Sorted Array is very similar. The previous topic was to give an array that would filter the arrays so that each number appeared only once.
With the groundwork of this inverted topic, use the same idea to complete it. The core idea is to understand that in order to continuously generate the final result, the element that has only once occurred is added to the existing result to update the final result. If it is understood to be deleted on the basis of the original, it will be more troublesome. In particular, Leetcode (26) of the data structure of the array, each deletion should be left to the right arrays, very time-consuming. The time cost of deleting a linked list element is less than the time cost of deleting an array element, but the idea of using a build rather than a deletion is good.
The code is as follows:
84ms too large collection
class Solution {public
:
listnode *deleteduplicates (ListNode *head) {
if head==null| | Head->next==null) return head
;
listnode* P=head;
listnode* q=head->next;
while (q!=null) {
if (q->val==p->val) {
q=q->next;
} else{
p->next=q;
p=q;
q=q->next;
}
}
p->next=null;
return head;
}
;
Update 1:2014-10-07
With the idea of generating a new array, refactoring
Class Solution {public
:
listnode *deleteduplicates (ListNode *head) {
if (head==null) return head
;
listnode* P=head;
listnode* q=head->next;
while (q!=null) {
if (q->val==p->val) {
p->next = q->next;
} else{
p=q;
}
Q = q->next;
}
return head;
}
;
Another kind of writing is basically the same, but the variable name is more clear, is this:
Class Solution {public
:
listnode *deleteduplicates (ListNode *head) {
if (head = = NULL) return head;
listnode* p_current = head;
listnode* P_next = head->next;
while (p_current!= null && p_next!= null) {
if (P_current->val = = p_next-> val) {
P_current->ne XT = p_next->next;
} else {
p_current = p_current->next;
}
P_next = p_next->next;
}
return head;
}
;