-->
当前位置:首页 > 题库 > 正文内容

程序填空题:Remove Nodes in Linked-List

Luz3年前 (2022-05-10)题库679
These functions are linked-list functions.

list_append is a function to append a new node at the end of the list.

list_remove is a function to remove nodes that have value k from list.

For example, for input:

1 2 3 4 8 5 8 8 6 7 9 -1
8

The output should be:

1 2 3 4 5 6 7 9


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

typedef struct _node {
int value;
struct _node* next;
} Node;

typedef struct {
Node* head;
} List;

void list_append(List *list, int x)
{
Node *p = (Node*)malloc(sizeof(Node));
p->value = x;
p->next = NULL;
Node *k;
for ( k = list->head;; k=k->next ) {
}
if ( k ) {
k->next = p;
} else {
;
}
}

void list_prt(const List *list)
{
for ( Node *p = list->head; p; p=p->next ){
printf("%d ", p->value);
}
printf("\n");
}

void list_free(List *list)
{
for ( Node *q,*p = list->head; p; p=q ){
q=p->next;
free(p);
}
list->head= NULL;
}

void list_remove(List *list, int k)
{
for ( Node *q=, *p=; ; ) {
if ( p->value == k ) {
if ( ) {
= p->next;
free(p);
p = ;
} else {
= p->next;
free(p);
p = ;
} // if (q)
} else {
q = p;
p = p->next;
} // if (p->value==k)
} // for
}

int main()
{
List list = {NULL};
int x;
while (1) {
scanf("%d", &x);
if ( x==-1 ) {
break;
}
list_append(&list, x);
}
int k;
scanf("%d", &k);
list_remove(&list, k);
list_prt(&list);
list_free(&list);
}








答案:
第1空:k&&k->next

第2空:list->head = p

第3空:NULL

第4空:list->head

第5空:p

第6空:q

第7空:q->next

第8空:q->next

第9空:list->head

第10空:list->head

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。