自己写的 关于链表的反转!欢迎给予意见!2012-2-18--2012-2-19

<pre>

#include<stdio.h>
#include<stdlib.h>
struct student 
{
int num;
float score;
struct student *next;
};                  //学生信息结构体 


main()
{
struct student *head=NULL,*head1=NULL;

struct student *create();     //链表的建立 
void input(struct student *p);    // 链表数据的输入 
void check(struct student *p);     //输入数据的检测 
struct student *f(struct student *p); //   反转链表 
void check1(struct student *p);       //反转后的链表的数据检测 

head=create();
        input(head);
        check(head);
        head1=f(head);
        check1(head1);
}


//链表的建立函数 
struct student *create()
{
int i;
struct student *head=NULL,*tail=NULL,*p=NULL;
for(i=0;i<8;i++)
  {p=(struct student *)malloc(sizeof(struct student));
   p->next=NULL;
   if(i==0) head=tail=p;
   else
        {tail->next=p;
      tail=p;
             };
  };
   return head;
}


//链表的数据输入函数 
void input(struct student *p)
{
int i;
printf("请输入8位学生信息:\n"); 
for(i=0;i<8;i++)
  {printf("学号:");
   scanf("%d",&p->num);
            printf("成绩:");
   scanf("%f",&p->score);
            printf("\n");
   p=p->next;
  };
}
//链表的数据检测函数(未反转) 
void check(struct student *p)
{
int i;
for(i=0;i<8;i++)
  {printf("学号:%d,成绩:%f\n",p->num,p->score);
   p=p->next;
  };
    printf("-------------------------\n");
}
//链表的反转函数 
struct student *f(struct student *p)
{
int i;
struct student *p1=NULL,*m=p,*temp=NULL,*temp1=NULL,*temp2=NULL;
temp2=p;
for(i=0;i<8;i++)      //实际上是再建立一个链表,头变尾,尾变头。 
   {
    if(i!=0) temp1=p1;
             p1=(struct student *)malloc(sizeof(struct student));
           p1->next=NULL;
       
    p1->num=p->num;
    p1->score=p->score;
    
    if(i==0) p1->next=NULL;
             else  p1->next=temp1;
             p=p->next;
     };               


   for(i=0;i<8;i++)        //把原来的未反转的链表内存释放 
         {temp=temp2;
  free(temp);
  temp=NULL;           //防止野指针 
  temp2=temp2->next;
 };
   return p1;
}
//反转后的链表检测 
void check1(struct student *p)
{
int i;
printf("反转后的链表为:\n");
for(i=0;i<8;i++)
  {printf("学号为:%d,成绩为%f\n",p->num,p->score);
   p=p->next;
  }
}

<pre>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值