实验题 链表倒序

来源:互联网 发布:同花顺炒股软件免费版 编辑:程序博客网 时间:2024/06/06 09:22

1104 [填空题]链表的倒序

时间限制:1000MS  内存限制:65536K
提交次数:2326 通过次数:1641

题型: 填空题   语言: 无限制

Description

下面程序,先创建一个链表,然后调用reverse函数,将链表中各结点变为倒序排列。请完成reverse函数,

#include "stdio.h" 
#include "malloc.h" 
#define LEN sizeof(struct student) 

struct student 

     long num; 
     int score; 
     struct student *next; 
}; 

struct student *create(int n) 
{  
     struct student *head=NULL,*p1=NULL,*p2=NULL; 
     int i; 
     for(i=1;i<=n;i++) 
     {  p1=(struct student *)malloc(LEN); 
        scanf("%ld",&p1->num); 
        scanf("%d",&p1->score); 
        p1->next=NULL; 
        if(i==1) head=p1; 
        else p2->next=p1; 
        p2=p1; 
      } 
      return(head); 


void print(struct student *head) 

    struct student *p; 
    p=head; 
    while(p!=NULL) 
    { 
        printf("%8ld%8d",p->num,p->score); 
        p=p->next; 
        printf("\n"); 
    } 


struct student *reverse(struct student *head) 

_______________________ 


main() 

    struct student *head,*stu; 
    int n; 
    scanf("%d",&n);   
    head=create(n); 
    print(head); 
    head=reverse(head); 
    print(head); 

输入样例

3(3 students)1(code of no.1 student)98(score of no.1 student)4(code of no.2 student)99(score of no.2 student)5(code of no.3 student)87(score of no.3 student)


输出样例

       1      98       4      99       5      87       5      87       4      99       1      98

这个题目一开始我是没想到怎么做的,本来是想弄个双向链表,但题目是填空题,链表已经定义,于是通过百度,在http://blog.csdn.net/sgbfblog/article/details/7754103,找到了两种方法,我最后选择了文章中阐述的迭代算法,提交后通过了

struct student *reverse(struct student *head){    struct student *p1 = head,*p2 = NULL,*p3 = NULL;    while (p1!= NULL) {        p2 = p1->next;        p1->next = p3;        p3 = p1;        p1 = p2;    }    return p3;}


原创粉丝点击