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

 

#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();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值