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->next)
  38. p = p->next;
  39. t = (struct link *)malloc(sizeof(struct link));
  40. t->data = data;
  41. t->next = NULL;
  42. p->next = t;
  43. }
  44. return p;
  45. }
  46.  
  47. void print(struct list *lst){
  48. struct link *p = lst->head;
  49. while(p){
  50. printf("%d\n", p->data);
  51. p = p->next;
  52. }
  53. }
  54.  
  55. int main(){
  56. struct list lst;
  57. lst.head = lst.tail = NULL;
  58. int in, i;
  59.  
  60. for(i = 1; i <= 3; i++){
  61. add_tail(&lst, i);
  62. }
  63. print(&lst);
  64. insert(&lst, 5);
  65. print(&lst);
  66. }
Success #stdin #stdout 0s 2288KB
stdin
Standard input is empty
stdout
1
2
3
1
2
3
5