#include
#include
#include
typedef struct node
{
int a;
struct node *next;
} NODE;
void main()
{
NODE * create(), *head;
NODE * SearchNode(NODE *head, int n);
void display(NODE *head);
NODE * DeleteNode(NODE *head, int n);
int n;
head = create();
if (head != NULL)
{
printf ("链表内容:\n");
display(head);
printf ("输入要删除的结点:");
scanf ("%d", &n);
head = DeleteNode(head, n);
if (head != NULL)
display(head);
else
printf ("链表被删除空了!\n");
}
else
printf ("链表为空!\n");
}
NODE * create()
{
NODE *head, *p, *q;
int a;
head = q = NULL;
srand ((unsigned) time (NULL));
while (1)
{
a = rand () % 100;
if (a != 30)
{
p = (NODE *) malloc (sizeof (NODE));
p->a = a;
if (head == NULL)
head = p;
else
q->next = p;
q = p;
}
else if (30 == a)
break;
}
if (q != NULL)
q->next = NULL;
return head;
}
void display(NODE *head)
{
NODE *h;
h = head;
while (h != NULL)
{
printf ("%3d", h->a);
h = h->next;
}
putchar (10);
}
NODE * SearchNode(NODE *head, int n)
{
NODE *prev, *h;
h = head;
while (h != NULL && h->a != n)
{
prev = h;
h = h->next;
}
return prev;
}
NODE *DeleteNode(NODE *head, int n)
{
int count = 0, flag = 0, num = 0;
NODE *prev, *h;
h = head;
while (h != NULL)
{
if (h->a == n)
count++;
h = h->next;
num++;
}
if (count == 0)
{
printf ("抱歉,没有找到要删除的结点!\n");
exit (0);
}
else
{
if (num == count)
count--;
while (head->a == n && count != 0)
{
h = head;
head = head->next;
free (h);
count--;
flag = 1;
}
if (count != 0 )
{
while (count--)
{
prev = SearchNode(head, n);
h = prev->next;
prev->next = h->next;
free (h);
}
}
else if (head->a == n)
{
printf ("链表被删除空了!\n");
free (head);
exit (1);
}
}
return head;
}