template <class T>
bool SingleList<T>::Delsame(T x)
{
Node<T> *head;
if(NULL == head) return head;
Node<T> *p=head;
Node<T> *first=NULL;
while(NULL != p){
if(p->element == x){
Node<T> *del =p;
p=p->link;
if(NULL!= first){
first->link=p;
}else{
head=p;
}
delete del;
} else{
first=p;
p=p->link;
}
}
return head;
}
代码如上,如 1 2 3 2 4 5 2
需要删除所有的2,
希望得到的结果是1 3 4 5
但目前得到的是1 2 3 4 5,
以及存在无法删除只有一个的元素、连续相同元素无法删除的问题,
如何修改可以将所有相同元素都删去呢?
There are a few questions here that I don’t understand very clearly. Please check them carefully
head
is defined at the beginning, but a NULL check is performed without assigning a value. Althoughhead
is not assigned a value, it is a random address and will not be NULL, but there is still a clear logical error herefirst
From the meaning of the word, it represents the first node, but you used it to represent the previous node. Is it easier to understand if it is renamedlast
? In the same way, it is recommended that the current pointerp
be renamedcurrent
.In the if condition, it seems that there is no need to define a
del
to point to p, becausep->next
is used later. After changing the connection, justdelete p
can be used, and thenp = head
Orp = first->next
to change the current pointer.Delsame
is defined asbool
, but the returned value ishead
No problems have been found in other logic for the time being. I think we can analyze and deal with the above problems first and then see the effect.
Give you a JavaScript algorithm reference
JavaScript mainly provides algorithm ideas, and those who have studied C/C++ should understand it. Then you can think about how to implement it in C++ based on this idea.
Note:
JavaScript refers to objects. This reference is similar to a C++ pointer and is different from a C++ reference
JavaScript does not require delete, so you need to add delete in the appropriate place after changing it to a C++ program.
Note that this is an interval that is closed on the left and open on the right, that is: data within the range of [first, last);
Usage example:
li.Remove(3)
where: begin and end are as follows:
The effect is as follows: