以下伪代码从链接列表中删除节点。
void list::erase()//Deletes a node
{
cout<< "Enter a position: ";
cin>> pos;
if(pos==1)
{
current=head;
head=head->ptr;
}
else
{
current=head;
for(i=0; i<pos-1; i++)
{
temp=current;
current=current->ptr;
}
temp->ptr=current->ptr;
}
cout<< "Erased string: " << current->content<<"\t";
current=head;
while(current!=NULL)
{
cout<<current->content<<"\t";
current=current->ptr;
}
}
我需要显示一条消息,以防我删除不在列表中的字符串:没有这样的字符串。我该怎么办?
以下伪代码搜索链表中的节点。
void list::search()//Searches a node
{
char str[50];
cout<<"Enter a string: ";
cin>> str;
current=head;
while(current!=NULL)
{
pos++;
if(!strcmp(current->content, str))
{
cout<< "Found at "<<pos;
}
current=current->ptr;
}
}
如果我在列表中搜索不的字符串并相应地显示消息:那里没有这样的字符串。我该怎么办?请帮忙。
答案 0 :(得分:0)
在输入while loop
之前设置变量found= false
。只有在找到要查找的字符串时才更改变量的值,然后在while之后进行打印:
found = false;
while(current!=NULL)
{
pos++;
if(!strcmp(current->content, str))
{
found = true;
break;
}
current=current->ptr;
}
if (found)
cout<< "Found at "<<pos;
else
cout<< "Not Found";