C中的这个过程应该根据链表的数据删除它的一个元素,但是每次我调用它时它都会卡住。我可以确认问题不在于声明列表的类型或相关内容。
void supprime(list *head, int data2) {//failed
//data2 refers to the value we are looking for
list p= *head, k;
if (*head== NULL)
printf("the list is empty");
else {
while ((p->data!= data2) && (!p)) {
k= p;
p= p->next;
}
if (p->data == data2) {
k->next= p->next;
free(p);
}
else
printf("This data is not availablen");
}
}
如果有人想要整个源代码,只是为了确保一切正常。
看来你的意思是像下面这样
int supprime( list *head, int data )
{
while ( *head && ( *head )->data != data ) head = &( *head )->next;
int success = *head != NULL;
if ( success )
{
list tmp = *head;
*head = ( *head )->next;
free( tmp );
}
return success;
}
考虑到 finction 不应发出消息。由函数的客户端决定是否发出消息。
这是一个演示程序。
#include <stdio.h>
#include <stdlib.h>
typedef struct cell
{
int data;
struct cell *next;
} cellule;
typedef cellule *list;
void affiche_liste( list head )
{
for ( ; head; head = head->next )
{
printf( "%d ", head->data );
}
}
int ajout_fin( list *head, int data )
{
list tmp = malloc( sizeof( *tmp ) );
int success = tmp != NULL;
if ( success )
{
tmp->data = data;
tmp->next = NULL;
while ( *head ) head = &( *head )->next;
*head = tmp;
}
return success;
}
int supprime( list *head, int data )
{
while ( *head && ( *head )->data != data ) head = &( *head )->next;
int success = *head != NULL;
if ( success )
{
list tmp = *head;
*head = ( *head )->next;
free( tmp );
}
return success;
}
int main(void)
{
const int N = 10;
list head = NULL;
int i = 0;
for ( ; i < N; i++ )
{
ajout_fin( &head, i );
affiche_liste( head );
putchar( 'n' );
}
while ( i )
{
supprime( &head, --i );
affiche_liste( head );
putchar( 'n' );
}
return 0;
}
它的输出是
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6
0 1 2 3 4 5
0 1 2 3 4
0 1 2 3
0 1 2
0 1
0