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 available\n");
}
}
如果有人想要entire source code,只是为了确保一切正常。
答案 0 :(得分:5)
看起来你的意思是以下
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;
}
考虑到检查不应发出消息。该功能的客户决定是否发出消息。
这是一个示范程序。
#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