链表的按值查找,未找到就把值放在链表的尾部
void LinkList_Locate ( node * head, int x )
{
node* p = head ;
int conunt=1;
while ( p != NULL && p->data != x )
{
p = p->next;
conunt++;
}
if( p == NULL )//我认为这句代码有问题
{
cout<<"wu"<<endl ;
node *s,*m;
s=new node;
s->data=x;
p->next=s;//还有这句代码,但不知道怎么改 求大侠帮助
s->next=NULL;
m=head;
while(m!=NULL)
{
cout<<m->data<<" ";
m=m->next;
}
}
else
cout<<p->data<<"位置是"<<conunt<<endl;
}
[解决办法]
[code=C/C++][/code]void LinkList_Locate ( node * head, int x )
{
if(NULL == head) return; // null link
node* p = head ;
int conunt = 1;
while ( p != NULL && p->data != x )
{
p = p->next;
conunt++;
}
if( p == NULL )//我认为这句代码有问题
{
cout<<"wu"<<endl ;
//locate the tail node
while(head->next != NULL)
{
cout<<m->data<<" ";
head = head->next;
}
//create a new node for the data x
node * newNode = new node(); //取有意义的变量名
newNode->data=x;
newNode->next=NULL;
//append it to the link
head->next = newNode;
}
else
{
cout<<p->data<<"位置是"<<conunt<<endl;
}
}
[解决办法]
格式化一下,未经测试。
- C/C++ code
void LinkList_Locate ( node * head, int x ) { if(NULL == head) return; // null link node* p = head ; int conunt = 1; while ( p != NULL && p->data != x ) { p = p->next; conunt++; } if( p == NULL )//not found { //cout<<"wu"<<endl ; //locate the tail node while(head->next != NULL) { cout<<m->data<<" "; head = head->next; } //create a new node for the data x node * newNode = new node(); //取有意义的变量名 newNode->data=x; newNode->next=NULL; //append it to the link head->next = newNode; } else { cout<<p->data<<"位置是"<<conunt<<endl; } } 