#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LEN sizeof (struct array)
struct array
{
char ch;
struct array *next;
};
int main()
{
struct array *deletea (struct array *h, char ch, int n); //删除字符'a'
void displist (struct array *head); //显示链表中内容
char str[100];
int n = 0, i, len, count = 0, j = 0;
struct array *head, *p1, *p2;
printf ("输入字符串:\n");
gets (str);
for (i=0; i<strlen(str); i++) //计算'a'的个数
if (str[i] == 'a')
count ++;
len = strlen (str);
p1 = p2 = (struct array *) malloc (LEN);
p1->ch = str[j++];
head = NULL;
while (len--)
{
n ++;
if (n == 1)
head = p1;
else
p2->next = p1;
p2 = p1;
p1 = (struct array *) malloc (LEN);
p1->ch = str[j++];
}
p2->next = NULL;
printf ("删除链表中'a'的结点:\n");
head = deletea (head, 'a', count);
displist (head);
printf ("\n");
return 0;
}
struct array *deletea (struct array *h, char c, int n)
{
struct array *FindNode (struct array *h, char c);//返回要删除结点的上一个结点
struct array *p, *r;
int flag = 0;
if (h == NULL)
{
printf ("链表为空!\n");
return h;
}
if (h->ch == c)
{
p = h;
h = h->next;
free (p);
n --;
flag = 1;
}
r = FindNode (h, 'a');
if (r==NULL && !flag)
printf ("没有找到要删除的结点!\n");
else
while(n--)
{
r = FindNode (h, 'a');
p = r->next;
r->next = p->next;
free (p);
}
return h;
}
struct array *FindNode (struct array *h, char c)
{
struct array *p = h, *q;
while (p!=NULL && p->ch!=c)
{
q = p;
p = p -> next;
}
if (p == NULL)
return NULL;
else
return q;
}
void displist (struct array *head)
{
while (head != NULL)
{
putchar (head->ch);
head = head -> next;
}
}
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/7c1ed21b0ef41bd555950a1957da81cb38db3d1d?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)