链表头插法,尾插法以及带头结点输出,不带头结点输出

爱被打了一巴掌 2023-02-14 06:50 111阅读 0赞

首先是头插法

头插法

  1. #include"stdio.h"
  2. #include"stdlib.h"
  3. typedef struct we
  4. {
  5. int data;
  6. struct we *next;
  7. }qwe;
  8. void shuchu(qwe *head)
  9. {
  10. qwe *p;
  11. printf("不带头结点的链表为:\n");//注意printf的次序
  12. p=head;
  13. for(;p!=NULL;)
  14. {
  15. printf("%d\t",p->data);
  16. p=p->next;
  17. }
  18. printf("\n");
  19. }
  20. qwe * yunxing(qwe *head)
  21. {
  22. qwe *p;
  23. int x;
  24. printf("请输入不为零的数\n");
  25. scanf("%d",&x);
  26. for(;x!=0;)
  27. {
  28. p=(qwe *)malloc(sizeof(qwe));
  29. p->data=x;
  30. p->next =head;
  31. head=p;
  32. scanf("%d",&x);
  33. }
  34. return head;
  35. }
  36. int main()
  37. {
  38. qwe *p,*head;
  39. head=NULL;
  40. p=yunxing(head);
  41. shuchu(p);
  42. return 0;
  43. }

以上的shuchu函数用的就是不带头结点的输出方式(p=head
不带头结点的输出方法

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
接下来是尾插法

尾插法

  1. #include"stdio.h"
  2. #include"stdlib.h"
  3. typedef struct we
  4. {
  5. int data;
  6. struct we *next;
  7. }qwe;
  8. void shuchu(qwe *head)
  9. {
  10. qwe *p;
  11. printf("带头节点的单链表为:\n");
  12. p=head->next ;
  13. for(;p!=NULL;)
  14. {
  15. printf("%d\t",p->data );
  16. p=p->next;
  17. }
  18. printf("\n");
  19. }
  20. qwe * yunxing(qwe *head)
  21. {
  22. int x;
  23. qwe *t,*last;
  24. t=(qwe *)malloc(sizeof(qwe));
  25. head=t;
  26. last=t;
  27. t->next =NULL;
  28. printf("请输入一个数:\n");
  29. scanf("%d",&x);
  30. for(;x!=0;)
  31. {
  32. t=(qwe *)malloc(sizeof(qwe));
  33. t->data=x;
  34. t->next =NULL;
  35. last->next =t;
  36. last=t;
  37. scanf("%d",&x);
  38. }
  39. return head;
  40. }
  41. int main()
  42. {
  43. qwe *p,*head;
  44. head=NULL;
  45. p=yunxing(head);
  46. shuchu(p);
  47. return 0;
  48. }

这个shuchu函数用的就是带头结点的输出方式(p=head->next
带头结点

发表评论

表情:
评论列表 (有 0 条评论,111人围观)

还没有评论,来说两句吧...

相关阅读