I. TopicsRemove duplicates from Sorted List IITotal Accepted :
37833 submissions:
151627My submissions
Given a sorted linked list, delete all nodes that has duplicate numbers, leaving only distinct numbers from th E original list.
for example,
1->2->3->3->4->4->5 , Return 1->2->5 .
given 1->1->1->2->3 , Return 2->3 .
Show TagsHas you met this question in a real interview? Yes No
Discuss
two. Problem solving skillsThis problem is similar to the Remove duplicates from Sorted list, however, the problem is to remove all the duplicated nodes, and the other one to retain a node for the duplicate element values, so this problem can be modified on the basis of another question. We can do this by setting a marker bit for removing the nodes that recur. This tag bit records whether the value of a node appears in the node in front of it, and if it does, discards the node, which resolves the problem. Similarly, this problem should also consider the input linked list only one node, for this case, directly return to the input list. For the last element of the list, determine whether to add it to the end of the output list by judging the marker bit.
Three. Implementing the Code
/*** Definition for singly-linked list.* struct ListNode {* int val;* listnode *next;* listnode (int x): Val (x ), Next (NULL) {}*};*/#include <iostream>struct listnode{int val; ListNode *next; ListNode (int x): Val (x), Next (NULL) {}};class solution{public:listnode *deleteduplicates (ListNode *head) { if (head = = null) {return null; }//Only have a single element if (Head->next = = NULL) {return new ListNode (head->v AL); } ListNode Header (10); ListNode *tail = &Header; ListNode *next = NULL; BOOL Isduplicates = false; while (head->next! = NULL) {next = head->next; if (head->val! = next->val) {if (! isduplicates) {tail->next = new ListNode (head->val); Update the tail tail = tail->next; } isduplicates = false; } else {isduplicates = true; } head = Next; } if (! isduplicates) {tail->next = new ListNode (head->val); } return header.next; }};
Four. ExperienceThis problem is not a lot of research on the algorithm, as long as the study of the chain list traversal and programming skills, as well as the boundary condition considerations, as long as careful, can do the right.
Copyright, welcome reprint, reproduced Please indicate the source, thank you
Leetcode_remove duplicates from Sorted List II