C语言问题,很简单的
2个回答
展开全部
#include <stdio.h>
#include <stdlib.h>
struct Element {
int var;
struct Element* next;
};
typedef struct Element List;
void* safe_malloc(int size) {
void* p = malloc(size);
if (p == NULL) {
fprintf(stderr, "malloc error!\n");
exit(1);
}
return p;
}
List* new_list() {
List* p = (List*)safe_malloc(sizeof(List));
p->var = 0;
p->next = NULL;
return p;
}
void list_append(List* list, int var) {
List* p = list;
while (p->next != NULL)
p = p->next;
p->next = (List*)malloc(sizeof(List));
p = p->next;
p->var = var;
p->next = NULL;
}
void print_list(List* list) {
int i;
int size = 0;
List* p = list;
while (p->next != NULL) {
p = p->next;
size++;
}
printf("size=%d:", size);
i = 0;
p = list;
while (p->next != NULL) {
if (i != 0)
putchar(' ');
printf("%d", p->next->var);
p = p->next;
i++;
}
putchar('\n');
}
void delete_last_var(List* list, int var) {
List* p = list;
List* var_p = NULL;
while (p->next != NULL) {
if (p->next->var == var)
var_p = p;
p = p->next;
}
if (var_p != NULL) {
p = var_p->next;
var_p->next = p->next;
free(p);
}
}
void delete_list(List* list) {
List* p = list;
List* q;
while (p->next != NULL) {
q = p;
p = p->next;
free(q);
}
}
int main(int argc, char *argv[]) {
List* list = NULL;
int repeat, list_size, var, del_var;
scanf("%d", &repeat);
while (repeat --> 0) {
scanf("%d", &list_size);
list = new_list();
while (list_size --> 0) {
scanf("%d", &var);
list_append(list, var);
}
scanf("%d", &del_var);
delete_last_var(list, del_var);
print_list(list);
delete_list(list);
}
return 0;
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
}*LinkList,*pNode,Node;
int deleteLast(LinkList head,int x) {
pNode q = 0,p = head;
while(p->next) {
if(p->next->data == x) q = p;
p = p->next;
}
if(q) {
p = q->next;
q->next = p->next;
return 1;
}
return 0;
}
void showList(LinkList head) {
pNode p = head->next;
while(p) {
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
void eraseList(LinkList head) {
pNode q,p = head;
while(p) {
q = p;
p = q->next;
free(q);
}
}
int main() {
int repeat,n,i,x;
pNode p;
LinkList head;
scanf("%d",&repeat);
while(repeat--) {
scanf("%d",&n);
head = (pNode)malloc(sizeof(struct node));
p = head;
for(i = 0; i < n; ++i) {
p->next = (pNode)malloc(sizeof(struct node));
scanf("%d",&p->next->data);
p = p->next;
}
p->next = 0;
showList(head);
scanf("%d",&x);
deleteLast(head,x);
showList(head);
eraseList(head);
}
return 0;
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询