Chinaunix首页 | 论坛 | 博客
  • 博客访问: 337248
  • 博文数量: 92
  • 博客积分: 2500
  • 博客等级: 少校
  • 技术积分: 960
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-21 19:38
文章分类

全部博文(92)

文章存档

2010年(71)

2009年(21)

我的朋友

分类: 嵌入式

2010-06-12 15:34:06

链表

用指针处理链表

#include
#define NULL 0    
    
 struct student
      {long num; float score; struct student *next; };
      main()
       {      struct student a,b,c,*head,*p;
            a. num=99101; a.score=89.5;
            b. num=99103; b.score=90;
            c. num=99107; c.score=85;
          
  head=&a;    a.next=&b;        b.next=&c;              
             c.next=NULL;     p=head;              
        do        {printf("%ld %5.1f\n",p->num,p->score);
                p=p->next;  } while(p!=NULL);
             }

 

库函数提供动态地开辟和释放存储单元的有关函数:

(1)    malloc函数

其函数原型为void *malloc(unsigned int size);其作用是在内存的动态存储区中分配一个长度为size的连续空间。此函数的值(即返回值)是一个指向分配域起始地址的指针(类型为void)。如果此函数未能成功地执行(例如内存空间不足),则返回空指针(NULL)

(2) calloc函数

        其函数原型为void *callocunsigned n, unsigned size;其作用是在内存的动态存储区中分配n个长度为size的连续空间。函数返回一个指向分配域起始地址的指针;如果分配不成功,返回NULL

        calloc函数可以为一维数组开辟动态存储空间,n为数组元素个数,每个元素长度为Size

(3) free函数

        其函数原型为void freevoid *p;其作用是释放由p指向的内存区,使这部分内存区能被其他变量使用。p是最近一次调用callocmalloc函数时返回的值。free函数无返回值。

 

 

 

#include

#include

#define NULL 0 //NULL代表0,用它表示“空地址

#define LEN sizeof(struct student)   //LEN代表struct //student类型数据的长度

  struct student

  {  long num;

      float score;      struct student *next;

  };int n; //n为全局变量,本文件模块中各函数均可使用它

 

 

struct student *creat()

  {   struct student *head;      struct student *p1,*p2;      n=0;

      p1=p2=( struct student*) malloc(LEN);

      scanf("%ld,%f",&p1->num,&p1->score);

      head=NULL;

      while(p1->num!=0)

       {  n=n+1;         if(n==1)head=p1;    

             else p2->next=p1;

             p2=p1;     

p1=(struct student*)malloc(LEN);

         scanf("%ld,%f",&p1->num,&p1->score);

        }

      p2->next=NULL;     

return(head);

 

}

 

 

void print(struct student *head)

        {struct student *p;

         printf("\nNow,These %d records are:\n",n);

  p=head;

         if(head!=NULL)

              do

               {printf("%ld %5.1f\n",p->num,p->score);

                 p=p->next;

                }while(p!=NULL);

        }

 

 

struct student *del(struct student *head,long num)

 {      

struct student *p1,*p2;

          if (head==NULL){printf("\nlist null!\n");goto end;}

          p1=head;    

 while(num!=p1->num&&p1->next!=NULL)                                           {p2=p1;p1=p1->next;}

if(num==p1->num)

         {if(p1==head)

head=p1->next;

          else p2->next=p1->next;

          printf("delete:%ld\n",num);         n=n-1;        }

       else printf("%ld not been found!\n",num);

end;return(head);

}

 

阅读(1016) | 评论(0) | 转发(0) |
0

上一篇:结构体

下一篇:s3c2440时钟文档

给主人留下些什么吧!~~