这道题的算法思想就是顺序建立一个链表,然后将表中的元素逐个与指定的值比较,若与p相等,则找到其前一个结点q,然后删除p结点即可。
代码如下:
#include <stdio.h>
#include <malloc.h>struct node{
int data;
struct node* next;
};
struct node* Createlist(int n){/*顺序建立链表*/
struct node* head,*tail,*p;
int i,d;
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
for(i=1;i<=n;i++){
p=(struct node*)malloc(sizeof(struct node));
scanf("%d",&d);
p->data=d;
p->next=NULL;
tail->next=p;
tail=p;
}
return head;
};
int main(){
int n,m;
struct node*head,*p,*q;
scanf("%d",&n);
head=Createlist(n);
printf("%d\n",n);
for(p=head->next;p!=NULL;p=p->next){
if(p==head->next)
printf("%d",p->data);
else
printf(" %d",p->data);
}
printf("\n");
scanf("%d",&m);
for(p=head->next;p!=NULL;p=p->next){/*找到与指定元素相等的元素的结点,并删除*/
if(p->data==m){
q=head;
while(q->next!=p)/*找到p的前一个结点q*/
q=q->next;
q->next=p->next;
n--;
}
}
printf("%d\n",n);
for(p=head->next;p!=NULL;p=p->next){
if(p==head->next)
printf("%d",p->data);
else
printf(" %d",p->data);
}
return 0;
}