fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct link{
  5. int data;
  6. struct link *next;
  7. };
  8.  
  9. struct list{
  10. struct link *head;
  11. struct link *tail;
  12. };
  13.  
  14. struct link * add_tail(struct list *lst, int value){
  15. struct link *item = (struct link *)malloc(sizeof(struct link));
  16. item->data = value;
  17. item->next = NULL;
  18. if(lst->head == NULL){
  19. lst->head = item;
  20. lst->tail = lst->head;
  21. }else{
  22. lst->tail->next = item;
  23. lst->tail = item;
  24. }
  25. return item;
  26. }
  27.  
  28. struct link * insert(struct list *lst, int data){
  29. struct link *p, *t;
  30. if(lst->head == NULL){
  31. p = (struct link *)malloc(sizeof(struct link));
  32. p->data = data;
  33. p->next = NULL;
  34. lst->head = p;
  35. }else{
  36. p = lst->head;
  37. while(p = p->next)
  38. ;
  39. p = (struct link *)malloc(sizeof(struct link));
  40. p->data = data;
  41. p->next = NULL;
  42. }
  43. return p;
  44. }
  45.  
  46. void print(struct list *lst){
  47. struct link *p = lst->head;
  48. while(p){
  49. printf("%d\n", p->data);
  50. p = p->next;
  51. }
  52. }
  53.  
  54. int main(){
  55. struct list lst;
  56. lst.head = lst.tail = NULL;
  57. int in, i;
  58.  
  59. for(i = 1; i <= 3; i++){
  60. add_tail(&lst, i);
  61. }
  62. print(&lst);
  63. insert(&lst, 5);
  64. print(&lst);
  65. }
Success #stdin #stdout 0s 2292KB
stdin
Standard input is empty
stdout
1
2
3
1
2
3