Title (Chinese)
Given a sorted list, delete all nodes containing duplicate numbers, and retain only those numbers that do not recur in the original list.
Example 1:
Input: 1 - > 2 - > 3 - > 3 - > 4 - > 4 - > 5 Output: 1->2->5
Example 2:
Input: 1 - > 1 - > 1 - > 1 - > 2 - > 3 Output: 2->3
English
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5 Output: 1->2->5
Example 2:
Input: 1->1->1->2->3 Output: 2->3
The idea of this question is the same as that of 83 at first, but it will be overtime if conditions are added directly to it.
First assign a NewNode dynamically outside, and then define a p to operate instead of NewNode.
C++
/** * 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||head->next==NULL) return head; ListNode* NewNode=new ListNode(0); NewNode->next=head; ListNode* p=NewNode; while(p->next){ ListNode *q = p->next; while (q->next!=NULL && q->next->val == q->val) q = q->next; if (q != p->next) p->next = q->next; else p = p->next; } return NewNode->next; } };
C
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* deleteDuplicates(struct ListNode* head){ if(head==NULL||head->next==NULL) return head; struct ListNode* NewNode=malloc(sizeof(struct ListNode)); NewNode->next=head; struct ListNode* p=NewNode; while(p->next){//At this point, head struct ListNode *q = p->next; while (q->next!=NULL && q->next->val == q->val) q = q->next; if (q != p->next) p->next = q->next; else p = p->next; } return NewNode->next; }
python3
# Definition for singly-linked list.
# class ListNode:
# def init(self, x):
# self.val = x
# self.next = None
class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: if head==None or head.next==None: return head; NewNode=ListNode(0); NewNode.next=head; p=NewNode; while p.next: q = p.next; while q.next!=None and q.next.val == q.val: q = q.next; if q != p.next: p.next = q.next; else: p = p.next; return NewNode.next;
javascript
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @return {ListNode} */ var deleteDuplicates = function(head) { if(!head||!head.next) return head; NewNode=new ListNode(0); NewNode.next=head; p=NewNode; while(p.next){ q = p.next; while (q.next && q.val== q.next.val) q = q.next; if (q != p.next) p.next = q.next; else p = p.next; } return NewNode.next; };