您的位置:首页 > 编程语言 > C语言/C++

链表的建立,输出,删除,插入运算的c语言实现

2011-08-20 20:16 861 查看
#include "Stdio.h"

#include "Conio.h"

#define NULL 0

#define TYPE struct stu

#define LEN sizeof(struct stu)

struct stu

{

int num;

int age;

struct stu *next;

};

/*构造链表*/

TYPE * creat(void)

{

struct stu *head,*pf,*pb;

int i,n;

printf("input number of node: ");

scanf("%d",&n);


pf=head=(TYPE *)malloc(LEN);

head->next=NULL;

for(i=0;i<n;i++)

{

pb=(TYPE *)malloc(LEN);

printf("input Number and Age\n");

scanf("%d%d",&pb->num,&pb->age);


if(pb->num<=0)

{ printf("input error,please retry");

i--;

}

else

{ pf->next=pb;

pb->next=NULL;

pf=pb;

}

}

return(head);

}

/*链表的删除节点*/


TYPE * delete(TYPE * head)

{

TYPE *pf,*pb;

int num;

if(head->next==NULL)

{ printf("\nempty list! cann't delete\n");

return head;

}


printf("Input the deleted number: ");

scanf("%d",&num);

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;

printf("The node is deleted\n");

}

else

printf("The node not been found!\n");

return head;

}


/*链表插入节点*/

TYPE * insert(TYPE * head)

{

TYPE *pb ,*pf,*pi;

printf("Input the inserted number and age: ");

pi=(TYPE *)malloc(LEN);

scanf("%d%d",&pi->num,&pi->age);


pb=head->next;

if(head->next==NULL)

{ head->next=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->next==pb)

{ head->next=pi;

pi->next=pb;

}

else

{pf->next=pi;

pi->next=pb;

}

}

else

{ pb->next=pi;

pi->next=NULL;

}

}

return head;

}


/*链表的输出*/

void print(TYPE * head)

{TYPE *p=head->next;

if(p==NULL) printf("list enmpty\n");

else

{

printf("Number\t\tAge\n");

while(p!=NULL)

{

printf("%d\t\t%d\n",p->num,p->age);

p=p->next;

}

}

}


void main(void)

{

TYPE * head,*pnum;

int n,num;

head=creat();

print(head);

head=delete(head);

print(head);

head=insert(head);

print(head);

getch();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐