我试图创建一个函数delz((,它从列表的末尾删除一个给定的数字,我递归地尝试了一个while循环,但我无法解决。示例:[3|next]-[4|next]-[3|next]-[7|next]----->[3|next]-[4|next]-[7|next]
list delz (int val, list l) {
if(l == NULL)
return NULL;
else {
list head = l;
list tmp = l;
list tail;
list temp;
while(l != NULL){
if(l->value == val) {
list tail = l->next;
head->next = tail;
}
temp = head;
head = tmp;
l = l->next;
}
return head;
}
}
typedef struct node {
int value;
struct node *next;
} node, *list;
如果通过引用将指向头节点的指针传递给函数,函数会更简单。
这是一个示范节目。我使用了我自己的单链表定义,因为您没有显示自己的定义。另外,为指针类型引入typedef也是个坏主意。
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int val;
struct Node *next;
};
void assign( struct Node **head, const int a[], size_t n )
{
if ( *head )
{
struct Node *tmp = *head;
*head = ( *head )->next;
free( tmp );
}
for ( size_t i = 0; i < n; i++ )
{
*head = malloc( sizeof( struct Node ) );
( *head )->val = a[i];
( *head )->next = NULL;
head = &( *head )->next;
}
}
void display( const struct Node *head )
{
for ( ; head != NULL; head = head->next )
{
printf( "%d -> ", head->val );
}
puts( "null" );
}
int remove_last( struct Node **head, int val )
{
struct Node **target = NULL;
for ( ; *head != NULL; head = &( *head )->next )
{
if ( ( *head )->val == val ) target = head;
}
int success = target != NULL;
if ( success )
{
struct Node *tmp = *target;
*target = ( *target )->next;
free( tmp );
}
return success;
}
int main(void)
{
int a[] = { 3, 4, 3, 7 };
const size_t N = sizeof( a ) / sizeof( *a );
struct Node *head = NULL;
assign( &head, a, N );
display( head );
int val = 3;
if ( remove_last( &head, val ) )
{
printf( "The last node with the value %d is removed.n", val );
}
display( head );
return 0;
}
程序输出为
3 -> 4 -> 3 -> 7 -> null
The last node with the value 3 is removed.
3 -> 4 -> 7 -> null