c语言-链表基本操作
上一篇 /
下一篇 2008-07-02 17:46:35
/ 个人分类:c语言
建立链表,删除结点,插入结点
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define NULL 0
struct stu
{
int num;
int age;
struct stu *next;
};
struct stu * creat(int n)
{
struct stu * head,*pb,*pf;
int i;
for(i=0;i<n;i++)
{
pb=(struct stu *)malloc(sizeof(struct stu));
printf("please input num and age\n");
scanf("%d %d",&pb->num,&pb->age);
if(i==0)
pf=head=pb;
else
pf->next=pb;
pb->next= NULL ;
pf=pb;
}
return(head);
}
struct stu * search(struct stu * head,int num)
{
struct stu *p;
p=head;
while(p->num!=num&&p->next!=NULL)
p=p->next;
if(p->num==num)
return p;
if(p->num!=num &&p->next==NULL)
printf("not found %d\n",num);
}
struct stu * delet(struct stu * head,int num)
{
struct stu *pb,*pf;
if(head==NULL)
{
printf("\nempty list!\n");;
return head;
}
pb=head;
while(pb->num!=num&&pb->next!=NULL)
{
pf=pb;
pb=pb->next;
}
if(pb->num==num)
{
if(pb==head)
head=pb->next;
else
{
pf->next=pb->next;
}
free(pb);
printf("The node is delete:\n");
}
else
printf("can not find %d",num);
return head;
}
struct stu * insert(struct stu * head,struct stu *pi)
{
struct stu * pb,*pf;
pb=head;
if(head==NULL)
{
head=pi;
pi->next=NULL;
}
else
{
while((pi->num>pb->num)&&(pb->next!=NULL))
{
pf=pb;
pb=pb->next;
}
if(pi->num<=pb->num)
{
if(head==pb)
head=pi;
else
pf->next=pi;
pi->next=pb;
}
else
{
pb->next=pi;
pi->next=NULL;
}
return head;
}
}
void print(struct stu * head)
{
printf("Number\t\tAge\n");
while(head!=NULL)
{
printf("%d\t\t%d\n",head->num,head->age);
head=head->next;
}
}
int main(void)
{
struct stu * head,*pnum;
int n,num;
printf("input numbers of node:");
scanf("%d",&n);
head=creat(n);
print(head);
printf("Input the deleted number: ");
scanf("%d",&num);
head=delet(head,num);
print(head);
printf("Input the inserted number and age: ");
pnum=(struct stu *)malloc(sizeof(struct stu));
scanf("%d%d",&pnum->num,&pnum->age);
head=insert(head,pnum);
print(head);
}
相关阅读:
- 《彻底搞定C指针》第2篇----指针是什么 (风过无痕, 2008-4-18)
- 彻底搞定C指针:指向指针的指针 (风过无痕, 2008-4-18)
- 彻底搞定C指针》第3篇--指针与数组名 (风过无痕, 2008-4-18)
- 《彻底搞定C指针》const int * pi/int * const pi的区别 (风过无痕, 2008-4-18)
- 彻底搞定C指针——函数参数的传递 (风过无痕, 2008-4-18)
- 《彻底搞定C指针》函数名与函数指针 (风过无痕, 2008-4-18)
- c语言常用函数与相对应的头文件 (chenmaochuan, 2008-5-25)
- c语言-sizeof (风过无痕, 2008-7-01)
- c语言文件操作-1 (风过无痕, 2008-7-01)
- c语言文件操作-2 (风过无痕, 2008-7-01)
收藏
举报
TAG:
c语言