创建一个链表,可以插入学生信息、删除学生信息

来源:互联网 发布:大学宿舍网络怎么样 编辑:程序博客网 时间:2024/04/30 09:45

//创建一个链表,可以插入学生信息、删除学生信息。

#include <iostream>

#define NULL 0

#define TYPE  struct student

#define LEN  sizeof (struct student)

using namespace std;

struct student 

{

int num;

int age;

struct student *next;

};

//创建一个链表

TYPE *creat(int n)

{

struct student *head,*pf,*pb;

int i;

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

{

pb=(TYPE *)malloc(LEN);

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

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

if(i==0){head=pb;pf=pb;}

   else  pf->next=pb;

   pb->next=NULL;

pf=pb;

}

return head;

}

//查找符合学号的节点

TYPE *search(TYPE *head,int num){

TYPE *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("查不到该学号所在的节点");

return head;

}

//删除学号指定的节点

TYPE *deleted(TYPE *head,int num){

TYPE *pf,*pb;

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);

}

else 

printf("THE NODE CANNOT FOUND!");

return head;

}

//在链表指定的位置插入一个节点

TYPE*insert(TYPE*head,TYPE *pi){

TYPE *pf,*pb;

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(pb==head)head=pi;

    else pf->next=pi;pi->next=pb;

}

else 

{

pb->next=pi;

pi->next=NULL;

}

}

return head;

}

//输出链表的元素

void print(TYPE *head){

     printf("number \t\tage\n");

     while(head!=NULL)

{

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

head=head->next;

}

}

int main(){

int n,num;

struct student *head,*p;

scanf("%d",&n);

head=creat(n);

print(head);

printf("input the deleted number:");

scanf("%d",&num);

head=deleted(head,num);

print(head);

printf("input the insert number and age:");

p=(TYPE *)malloc(LEN);

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

head=insert(head,p);

print(head);

return 0;

}

 

原创粉丝点击