题目:
将一个链表中元素值为x的结点删除。(链表数据域为整数,初始长为6个元素) **输入提示信息:"输入数组%d个元素的值。\n" **输入格式:"%d" **输出提示:"此链表各个结点的数据域为:" **输出格式:"%d " **输入提示信息:"输入要删除的数据x: " **输入格式:"%d" **输出提示: "删除后链表各个结点的数据域为:" **输出格式:"%d "
#include<stdio.h>
#include<stdlib.h>
#define N 6
struct note
{
int i;
struct note*next;
};
void freetem(struct note *head)
{
struct note *pre=head;
struct note *aft=head;
while(aft!=NULL)
{
pre=aft;
aft=pre->next;
free(pre);
}
}
struct note* find(struct note*head,int x)
{
struct note*p=head;
struct note*pre=head;
if(head->i==x)
{
p=p->next;
head=p;
pre->next=NULL;
free(pre);
return head;
}
while(p!=NULL&&p->next!=NULL)
{
pre=p;
p=p->next;
if(p->i==x)
{
pre->next=p->next;
p->next=NULL;
free(p);
p=pre;
}
}
return head;
}
main()
{
int num[N],i=0;
struct note*head=NULL;
head=(struct note*)malloc(sizeof(struct note));
if(head==NULL)
{
printf("error");
exit(0);
}
printf("输入数组%d个元素的值。\n",N);
scanf("%d",&num[i]);
head->i=num[i];
struct note*p=head;
for(i=1;i<N;i++)
{
scanf("%d",&num[i]);
struct note *pst=(struct note*)malloc(sizeof(struct note));
if(head==NULL)
{
printf("error");
exit(0);
}
pst->i=num[i];
p->next=pst;
pst->next=NULL;
p=pst;
}
printf("此链表各个结点的数据域为:\n");
p=head;
while(p!=NULL)
{
printf("%d ",p->i);
p=p->next;
}
printf("输入要删除的数据x: ");
int x;
scanf("%d",&x);
struct note*newhead=find(head,x);
printf("删除后链表各个结点的数据域为:");
p =newhead;
while(p!=NULL)
{
printf("%d ",p->i);
p=p->next;
}
freetem(head);
}