链表的逆转:巧妙之处在于递归的使用,自我炫耀一番,嘿嘿。

#include <stdio.h>
#include <stdlib.h>

#define LEN sizeof(struct student)
#define FORMANT() \
                  printf("==================================\n");\
                  printf("num     eng     math     avg(auto)\n");\
                  printf("==================================\n")

struct student
{
       int    num;
       float  english;
       float  math;
       float  avg;
       struct student *next;
};

int n = 0;

struct student *creat();
void prt(struct student *head);
struct student *exchange(struct student *head);

int main(int argc, char *argv[])
{
  struct student stu, *head;
  int pos,position;
 
  printf("创建链表:\n");
  head = creat();
  prt(head);
  printf("\n逆转链表:\n");
  head = exchange(head);
  prt(head);
 
  system("PAUSE");   
  return 0;
}

struct student *creat()
{
       struct student *p1, *p2, *head = NULL;
      
       p1 = p2 = (struct student *)malloc(LEN);
       printf("请输入学生的信息:\n");
       FORMANT();
       scanf("%d%f%f", &p1->num,&p1->english,&p1->math);
       p1->avg = (p1->english + p1->math)/2;
      
       while(p1->num != 0)
       {
               n++;
               if(n == 1)
               {
                    head = p1;
               }     
               else
               {
                   p2->next = p1;
               }
               p2 = p1;
               p1 = (struct student *)malloc(LEN);
               scanf("%d%f%f", &p1->num,&p1->english,&p1->math);
               p1->avg = (p1->english + p1->math)/2;
       }   
       p1->next = NULL;
       return head;
}

void prt(struct student *head)
{
     struct student *p1;
     p1 = head;
     printf("\n显示链表:\nnow there are %d datas.\n",n);
     FORMANT();
     while(p1 != NULL)
     {
           printf("%-8d%-8.2f%-9.2f%-8.2f\n", p1->num, p1->english, p1->math, p1->avg);
           p1=p1->next;
     }
}

struct student *exchange(struct student *head)
{
       struct student *p1, *p2;
      
       p1 = head;
       if(p1->next == NULL)
       {
            head = p1;
       }
       else
       {
           p2 = p1->next;
           head = exchange(p2);
           p2->next = p1;
           p1->next = NULL;
       }
       return head;
}