69,374
社区成员
发帖
与我相关
我的任务
分享
void delet(int disnum, n *head)
{
n p, q;
p = q = *head;
while (p) {
if (p->data == disnum) {
if (p == *head) {
*head = (*head)->next;
free(p);
p = q = *head;
continue;
} else {
q->next = p->next;
free(p);
p = q;
p = p->next;
continue;
}
}
q = p;
p = p->next;
}
}
试一下这个版本。
以下是我的测试代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
}*n;
n create_link(int num)
{
int i;
n p, q, phead = NULL;
for (i = 0; i < num; i++) {
p = (n)malloc(sizeof (struct node));
if (!p) {
fprintf(stderr, "malloc error!\n");
exit(-1);
}
scanf("%d", &p->data);
if (!phead) {
phead = p;
q = p;
} else {
q->next = p;
q = p;
}
}
q->next = NULL;
return phead;
}
void print_link(n phead)
{
n p = phead;
while (p) {
printf("%d\t", p->data);
p = p->next;
}
putchar(10);
}
void delet(int disnum, n *head)
{
n p, q;
p = q = *head;
while (p) {
if (p->data == disnum) {
if (p == *head) {
*head = (*head)->next;
free(p);
p = q = *head;
continue;
} else {
q->next = p->next;
free(p);
p = q;
p = p->next;
continue;
}
}
q = p;
p = p->next;
}
}
int main(void)
{
int num;
n head;
scanf("%d", &num);
head = create_link(num);
print_link(head);
scanf("%d", &num);
delet(num, &head);
print_link(head);
return 0;
}