当前位置:   article > 正文

【尾插法】表尾插入法构造链表 (10 分)_本题实现链表的构造,采用表尾插入法构造链表,输出表中所有元素。

本题实现链表的构造,采用表尾插入法构造链表,输出表中所有元素。

本题实现链表的构造,采用表尾插入法构造链表,输出表中所有元素。

函数接口定义:

  1. 函数接口:
  2. ptr creat( );//构造链表
  3. void output(ptr p);//输出链表元素

其中p 是用户传入的参数。creat函数返回链表的头指针,输入在creat函数中输入,以0表示输入结束。output函数输出链表元素,以一个空格隔开。

裁判测试程序样例:

  1. #include <stdio.h>
  2. #include <malloc.h>
  3. typedef struct node
  4. {
  5. int data;
  6. struct node *next;
  7. }snode,*ptr;
  8. ptr creat( );//构造链表
  9. void output(ptr p);/输出链表元素
  10. int main()
  11. {
  12. ptr head;
  13. head=creat();
  14. output(head);
  15. return 0;
  16. }
  17. /* 请在这里填写答案 */

输入样例:

1 2 3 0

输出样例:

1 2 3 

代码区: 

  1. ptr creat( )
  2. {
  3. struct node *p,*head,*tail;//头指针,尾指针
  4. head=tail=NULL;
  5. int x=-100;
  6. while(scanf("%d",&x)&&x!=0)
  7. {
  8. //scanf("%d",&x);
  9. p=(struct node*)malloc(sizeof(struct node));//动态内存分配申请数组空间
  10. p->data = x;
  11. p->next = NULL;
  12. if(head == NULL){
  13. head = tail = p;
  14. }
  15. else{
  16. tail->next = p;
  17. tail = p;
  18. }
  19. }
  20. return head;
  21. }
  22. //构造链表
  23. void output(ptr p)
  24. {
  25. //struct Node *p = head;
  26. //printf("%d",p->data);
  27. //p = p->next;
  28. while(p){
  29. printf("%d ",p->data);
  30. p=p->next;
  31. }
  32. }//输出链表元素

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/777291
推荐阅读
相关标签
  

闽ICP备14008679号