Advertisement
neversmile

Đảo ngược 1 dãy số

Jun 20th, 2013
330
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. typedef int element_type;
  4. struct node {
  5. element_type element;
  6. struct node *next;
  7. };
  8.  
  9. void khoi_tao_ds(struct node **first, struct node **last)
  10. {
  11. *first = *last = NULL;
  12. }
  13.  
  14. void insert(element_type e, struct node **first, struct node **last)
  15. {
  16. struct node *tmp;
  17. tmp = (struct node*) malloc(sizeof(struct node));
  18. tmp->element = e;
  19. tmp->next = NULL;
  20. if (*first == NULL)
  21. *first = *last = tmp;
  22. else
  23. {
  24. (*last)->next = tmp;
  25. (*last) = (*last)->next;
  26. }
  27. }
  28.  
  29. void xoa_ds(struct node **first, struct node **last)
  30. {
  31. struct node *tmp;
  32. tmp = *first;
  33. while (tmp != NULL)
  34. {
  35. tmp = (*first)->next;
  36. free(*first);
  37. *first = tmp;
  38. }
  39. *first = *last = NULL;
  40. }
  41.  
  42. void nhap_ds(struct node **first, struct node **last)
  43. {
  44. element_type e;
  45. printf("\nNhap cac gia tri so (-1) de ket thuc : ");
  46. do {
  47. scanf("%d", &e);
  48. if (e != -1)
  49. insert(e, first, last);
  50. } while (e != -1);
  51. }
  52.  
  53. void print_ds(struct node *first)
  54. {
  55. struct node *tmp;
  56.  
  57. tmp = first;
  58. while (tmp != NULL)
  59. {
  60. printf("%d ", tmp->element);
  61. tmp = tmp->next;
  62. }
  63. }
  64.  
  65. void daonguocds(struct node **first, struct node **last)
  66. {
  67. struct node *before = NULL, *after, *cursor ;
  68.  
  69. if (*first != NULL)
  70. {
  71. after = *first;
  72. cursor = after->next;
  73. *last = *first;
  74. while (cursor != NULL)
  75. {
  76. after->next = before;
  77. before = after;
  78. after = cursor;
  79. cursor = cursor->next;
  80. }
  81. after->next = before;
  82. *first = after;
  83. }
  84. }
  85.  
  86. void main()
  87. {
  88. struct node *first, *last;
  89.  
  90. khoi_tao_ds(&first, &last);
  91. nhap_ds(&first, &last);
  92. printf("Danh sach ban dau : ");
  93. print_ds(first);
  94. daonguocds(&first, &last);
  95. printf("\nSau khi dao nguoc : ");
  96. print_ds(first);
  97. xoa_ds(&first, &last);
  98. getch();
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement