美文网首页
【MAC 上学习 C++】Day 55-2. 实验11-2-3

【MAC 上学习 C++】Day 55-2. 实验11-2-3

作者: RaRasa | 来源:发表于2019-10-18 19:14 被阅读0次

    实验11-2-3 逆序数据建立链表 (20 分)

    1. 题目摘自

    https://pintia.cn/problem-sets/13/problems/603

    2. 题目内容

    本题要求实现一个函数,按输入数据的逆序建立一个链表。

    函数接口定义:

    struct ListNode *createlist();
    函数createlist利用scanf从输入中获取一系列正整数,当读到−1时表示输入结束。按输入数据的逆序建立一个链表,并返回链表头指针。链表节点结构定义如下:

    struct ListNode {
    int data;
    struct ListNode *next;
    };

    输入样例:

    1 2 3 4 5 6 7 -1

    输出样例:

    7 6 5 4 3 2 1

    3. 源码参考
    #include <iostream>
    #include <stdlib.h>
    
    using namespace std;
    
    struct ListNode {
        int data;
        struct ListNode *next;
    };
    
    struct ListNode *createlist();
    
    int main()
    {
        struct ListNode *p, *head = NULL;
    
        head = createlist();
        for ( p = head; p != NULL; p = p->next )
        {
          cout << p->data << " ";
        }
    
        cout << endl;
    
        return 0;
    }
    
    struct ListNode *createlist()
    {
      struct ListNode *p, *h;
      int n;
    
      h = NULL;
      cin >> n;
      while(n != -1)
      {
        p = (struct ListNode*)malloc(sizeof(struct ListNode));
        
        p->data = n;
        p->next = NULL;
        
        if(h == NULL)
        {
          h = p;
        }
        else
        {
          p->next = h;
        }
        
        h = p;
        cin >> n;
      }
      
      return h;
    }
    

    相关文章

      网友评论

          本文标题:【MAC 上学习 C++】Day 55-2. 实验11-2-3

          本文链接:https://www.haomeiwen.com/subject/uhbhmctx.html