从链表的查找开始,不知道哪错了,我敲了好几遍了,每天都有点错误;12月份考研考c语言就怕考这个;
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node,*pnode;
int main ()
{
pnode createList(int);
pnode createNode();
void outputList(pnode);
pnode find();
pnode deleteNode();
pnode insert();
int m,n;
printf("请输入要生成几个节点? ");
scanf("%d",&n);
pnode head=createList(n);
outputList(head);
printf("请输入要删除的数据:");
scanf("%d",&m);
pnode p=find(m);
head=deleteNode(head,p);
outputList(head);
putchar(10);
printf("请输入要插在第几个位置");
scanf("%d",&n);
head=insert(head,n);
outputList(head);
return 0;
}
pnode createNode()
{
pnode pnew;
pnew=(pnode)malloc(sizeof(node));
if(pnew==NULL)
{
printf("内存申请失败");
exit(0);
}
printf("请输入数据:");
scanf("%d",&(pnew->data));
pnew->next=NULL;
return pnew;
}
pnode createList(int n)
{
pnode head,pend;
int i;
if(n>=1)
{
head=createNode();
pend=head;
}
for(i=2;i<=n;i++)
{
pnode pnew =createNode();
pend->next=pnew;
pend=pnew;
}
if(n<1)
{
printf("输入不对哦");
exit(0);
}
return head;
}
void outputList(pnode head)
{
pnode p=head;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
}
pnode find(pnode head,int m)
{
pnode p=head;
while(p!=NULL&&p->data!=m)
p=p->next;
if(p==NULL)
{
printf("链表中不存在此数据!");
return p;
}
return p;
}
pnode deleteNode(pnode head,pnode p)
{
if(p==NULL)
exit(0);
else if(p==head)
{
head=head->next;
return head;
}
else
{
pnode q=head;
while(q->next!=p)
q=q->next;
q->next=p->next;
free(p);
return head;
}
return head;
}
pnode insert(pnode head,int n)
{
pnode p=head;
int i=1;
while(p!=NULL&&i<n-1)
{
p=p->next;
i++;
}
if(p==NULL&&i>n-1)
{
printf("输入非法值!");
exit(0);
}
pnode pnew=createNode();
pnew->next=p->next;
p->next=pnew;
return head;
}