链表(单向)

来源:互联网 发布:python抓取淘宝数据 编辑:程序博客网 时间:2024/05/16 18:58

二、算法

1.算法的设计依赖于数据的逻辑结构,而算法的实现则取决于特定的物理结构。

2.算法是对特定问题求解步骤的一种描述,是指令的有限序列。

五大特性为:有穷、确定、可行、有输入、有输出。

 

三、线性表:1.顺序表 2.链表

链表,较数组而言空间利用率上占优势,可以动态灵活地分配内存空间,但是不能随机读取。其基本操作为创建,插入,删除,查找,排序等,代码如下:

 

#include <stdio.h>
#include <stdlib.h>
struct student
{
    float score;
    int num;
    struct student *next;
};
struct student *creat()      //建立__链表
{
    struct student *head,*end,*fla,*next;
    head=end=fla=NULL;
    end=next=(struct student *)malloc(sizeof(struct student));
    scanf("%d%d",&fla->num,&fla->score);
    fla->next=NULL;
    while(fla->num!=0)
    {
        if(head==NULL)
            head=fla;
        else
            end->next=fla;
        end=fla;
        fla=(struct student *)malloc(sizeof(struct student));
        scanf("%d%f",&fla->num,&fla->score);
        fla->next=NULL;
    }
    return head;
}
void print(struct student *head)   //输出__单向链表
{
 struct student *cur;
 printf("now,records are:");
 cur=head;
 while(cur!=NULL)
 {
  printf("%d\t%f\n",cur->num,cur->score);
  cur=cur->next;
 }
}
struct student *delet(struct student *head,long id)      //删除__学号为id的结点
{
    struct student *p,*cur;
    if(head==NULL)
        printf("\nList is empty.\n");
    else
    {
        cur=head;
        while(id!=cur->num&&cur->next!=NULL)
            p=cur;
        cur=cur->next;
        if(id==cur->num)
        {
            if(cur==head)
                head=cur->next;
            else
                p->next=cur->next;
                printf("\n%d  delet\n",id);
        }
        else
            printf("%d not been found.\n",id);
    }
    return head;
}
struct student *insert(struct student *head,struct student *stu)    //将std结点插入__链表中
{
    struct student *fla,*cur,*p;
    cur=head;
    fla=stu;
    if(head==NULL)
    {
        head=fla;
        fla->next=NULL;
    }
    else
    {
        while((fla->num>cur->num)&&(cur->next!=NULL))
        {
            p=cur;
            cur=cur->next;
        }
        if(fla->num<=cur->num)
        {
            if(head=cur)
                head=fla;
            else
                p->next=fla;
            fla->next=cur;
        }
        else
        {
            cur->next=fla;
            fla->next=NULL;
        }
    }
    return head;
}
int main()
{
 struct student  *head,*p1;
    int num;
    head=creat();
    print(head);
    printf("Input the deleted number:");
    scanf("%d",&num);
    head=delet(head,num);
    print(head);
    printf("please input the insert node:");
    p1=(struct student *)malloc(sizeof(struct student));
    scanf("%d%f",&p1->num,&p1->score);
    head=insert(head,p1);
    print(head);
 return 0;
}

 

单向链表的应用有线性表的归并、一元多项式的表示和加减运算、多项式运算、约瑟夫问题等。

 

0 0
原创粉丝点击