zoukankan      html  css  js  c++  java
  • 逆序输出的数列

    此题为网易云课堂《C语言程序设计进阶(翁凯)》第五周编程作业,参照课件中老师给的示范完成,未定义List结构体及未使用哨兵节点,题目要求及代码如下

    /*
        Name: 
        Copyright: 
        Author: 
        Date: 30/03/15 21:01
        Description: 
    题目内容:
    你的程序会读入一系列的正整数,预先不知道正整数的数量,一旦读到-1,就表示输入结束。然后,按照和输入相反的顺序输出所读到的数字,不包括最后标识结束的-1。
    
    输入格式:
    一系列正整数,输入-1表示结束,-1不是输入的数据的一部分。
    
    输出格式:
    按照与输入相反的顺序输出所有的整数,每个整数后面跟一个空格以与后面的整数区分,最后的整数后面也有空格。
    
    输入样例:
    1 2 3 4 -1
    
    输出样例:
    4 3 2 1
    */
    
    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct Node
    {
        int value;
        struct Node * next;
    }Node;
    
    Node * add(Node * head, int number);
    Node * inverse(Node * head);
    void print(Node * head);
    
    int main()
    {
    //    freopen("in.txt", "r", stdin); // for test
        
        Node * head;
        int number;
        
        head = NULL;
        while(scanf("%d", &number) && number != -1)
            head = add(head, number);
        
        head = inverse(head);
        
        print(head);
        
    //    fclose(stdin); // for test
        
        return 0;
    }
    
    Node * add(Node * head, int number)
    {
        // add to linked-list
        Node * p = (Node *)malloc(sizeof(Node));
        p->value = number;
        p->next = NULL;
        // find the last
        Node * last = head;
        if(last)
        {
            while(last->next)
                last = last->next;
            // attach
            last->next = p;
        }
        else
            head = p;
            
        return head;
    }
    
    Node * inverse(Node * head)
    {
        if(head != NULL && head->next != NULL)
        {
            Node * p, * q, * tmp;
            p = head;
            q = p->next;
            while(q->next)
            {
                tmp = q->next;
                q->next = p;
                p = q;
                q = tmp;
            }
            q->next = p;
            head->next = NULL;
            head = q;
        }
        
        return head;
    }
    
    void print(Node * head)
    {
        Node * p, * tmp;
        
        p = head;
        if(p)
        {
            while(p)
            {
                printf("%d", p->value);
                tmp = p;
                p = p->next;
                if(p)
                    printf(" ");
                else
                    printf("
    ");
                free(tmp);
            }
        }
    }
  • 相关阅读:
    第六篇 面向对象
    第四篇 函数
    基本http服务性能测试(Python vs Golang)
    七种常见经典排序算法总结(C++)
    461. Hamming Distance and 477. Total Hamming Distance in Python
    2. Add Two Numbers——Python
    21. Merge Two Sorted Lists —— Python
    求两个数字的最大公约数-Python实现,三种方法效率比较,包含质数打印质数的方法
    20. Valid Parentheses
    Python列表去除重复元素
  • 原文地址:https://www.cnblogs.com/qingkai/p/4381162.html
Copyright © 2011-2022 走看看