C语言的那些小秘密之链表(一)

发表于:2011-12-13 09:36

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:bigloomy(CSDNblog)    来源:51Testing软件测试网采编

分享:

#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <stdlib.h>
#define N 3
#undef  _EXAM_ASSERT_TEST_    //禁用
//#define  _EXAM_ASSERT_TEST_   //启用
#ifdef _EXAM_ASSERT_TEST_     //启用断言测试
 void assert_report( const char * file_name, const char * function_name, unsigned int line_no )
{
 printf( "\n[EXAM]Error Report file_name: %s, function_name: %s, line %u\n",
         file_name, function_name, line_no );
  abort();
}
#define  ASSERT_REPORT( condition )       \
 do{       \
 if ( condition )       \
  NULL;        \
 else         \
  assert_report( __FILE__, __func__, __LINE__ ); \
 }while(0)
#else // 禁用断言测试
#define ASSERT_REPORT( condition )  NULL
#endif /* end of ASSERT */
typedef enum _SListReturn
{
 SLIST_RETURN_OK
}SListReturn;
typedef struct node
{
 char name[10];
 int score;
 struct node *link;
}stud;
stud * creat(int n)
{
 stud *p,*h,*s;
 int i;
 if((h=(stud *)malloc(sizeof(stud)))==NULL)
 {
  printf("分配内存空间失败!");
  exit(0);
 }
 h->name[0]='\0';
 h->score=0;
 h->link=NULL;
 p=h;
 for(i=0;i<n;i++)
 {
  if((s= (stud *) malloc(sizeof(stud)))==NULL)
  {
   printf("分配内存空间失败!");
   exit(0);
  }
 p->link=s;
 printf("请输入第%d个人的姓名:",i+1);
 scanf("%s",s->name);
 printf("请输入第%d个人的成绩:",i+1);
 scanf("%d",&s->score);
 s->link=NULL;
 p=s;
 }
 return h;
}
SListReturn destroy(stud* head)
{
 stud* tmp,*next;
 tmp=head;
 while(tmp!=NULL)
 {
  next=tmp->link;
  tmp->link=NULL;
  free(tmp);
  tmp=next;
 } 
 return SLIST_RETURN_OK;
}
SListReturn print(stud* head)
{
 stud* tmp=head->link;
 while(tmp!=NULL)
 {
  printf("%s的成绩为%d\t",tmp->name,tmp->score);
  tmp=tmp->link;
 }
 return SLIST_RETURN_OK;
}
void main()
{
 int number;
 stud *head;
 number=N;
 head=creat(number);
 ASSERT_REPORT(print(head)==SLIST_RETURN_OK);
 ASSERT_REPORT(destroy(head)==SLIST_RETURN_OK);
}

  运行结果为:

  root@ubuntu:/home/paixu# ./tt
  请输入第1个人的姓名:rewq
  请输入第1个人的成绩:123
  请输入第2个人的姓名:fdsa
  请输入第2个人的成绩:456
  请输入第3个人的姓名:vcxz
  请输入第3个人的成绩:789
  rewq成绩为123  fdsa成绩为456  vcxz成绩为789

42/4<1234>
春暖花开更文季,点击参与还有惊喜礼品~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计

法律顾问:上海漕溪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2023
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号