gpt4 book ai didi

c 程序从给定链表中删除元素并在删除后打印整个列表

转载 作者:行者123 更新时间:2023-11-30 19:33:43 24 4
gpt4 key购买 nike

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <ctype.h>

struct Stud
{
char name[20];
struct Stud *next;
};

struct Stud *hptr=NULL,*tptr;
//char data[20];


void deleteKey(struct Stud *hptr,char data[20])
{
struct Stud * temp = hptr, *prev;
while (temp != NULL && temp->name == data)
{
hptr = temp->next;
free(temp);
temp = hptr;
}
while (temp != NULL)
{
while (temp != NULL && temp->name != data)
{
prev = temp;
temp = temp->next;
}


if (temp == NULL) return;


prev->next = temp->next;

free(temp);


temp = prev->next;
}
}




void createList(char *s)
{
struct Stud *nptr;
nptr=(struct Stud *)malloc(sizeof(struct Stud));
strcpy(nptr->name,s);
if(hptr==NULL)
hptr=tptr=nptr;
else
tptr->next=nptr;
tptr=nptr;
nptr->next=NULL;
}


void display(){
while(hptr!=NULL) {
printf("%s ",hptr->name);
hptr=hptr->next;
}


}


void main(){
int i,n;
char str1[20];
char s[20];
scanf("%d",&n);
for(i = 0; i < n; i++) {
scanf("%s",str1);
createList(str1);
}
scanf("%s",s);
display();
deleteKey(hptr, s);
display();
}

我没有得到所需的输出。请纠正我将参数传递给deleteKey,并建议我如果代码中有任何问题。 例如: 输入: 5 克米特 津图 斯尼斯特 西比特 恩 git 西比特 输出: 克米特 津图 斯尼斯特 ngit

最佳答案

您必须通过引用将头节点传递给函数,因为它可以在函数内更改。

此外,您还必须使用标准函数 strcmp 来比较字符串。

在这个表达式中

temp->name == data

比较两个数组的首字符地址,明显不相等。

这是一个演示程序,展示了如何实现该功能。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Stud
{
char name[20];
struct Stud *next;
};

int deleteKey( struct Stud **head, const char *name )
{
while ( *head && strcmp( ( *head )->name, name ) != 0 )
{
head = &( *head )->next;
}

int success = *head != NULL;

if ( success )
{
struct Stud *node = *head;
*head = ( *head )->next;
free( node );
}

return success;
}

int push_front( struct Stud **head, const char *name )
{
struct Stud *node = malloc( sizeof( *node ) );
int success = node != NULL;

if ( success )
{
strncpy( node->name, name, sizeof( node->name ) );
node->name[sizeof( node->name ) - 1] = '\0';
node->next = *head;
*head = node;
}

return success;
}

void display_list( struct Stud **head )
{
for ( struct Stud *current = *head; current != NULL; current = current->next )
{
printf( "%s ", current->name );
}
}

int main(void)
{
struct Stud *head = NULL;

push_front( &head, "Bob" );
push_front( &head, "Peter" );
push_front( &head, "Margarite" );

display_list( &head );
putchar( '\n' );

deleteKey( &head, "Margarite" );

display_list( &head );
putchar( '\n' );

deleteKey( &head, "Bob" );

display_list( &head );
putchar( '\n' );

deleteKey( &head, "Peter" );

display_list( &head );
putchar( '\n' );

return 0;
}

程序输出为

Margarite Peter Bob 
Peter Bob
Peter

关于c 程序从给定链表中删除元素并在删除后打印整个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45060158/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com