STIVA - implementare cu lista inlantuita


/ Published in: C
Save to your folder(s)

stiva


Copy this code and paste it in your HTML
  1. #include <stdio.h>
  2. #include <malloc.h>
  3. #include <stdlib.h>
  4.  
  5. //implementare stiva
  6.  
  7. struct numar{
  8. int valoare;
  9. struct numar *next;
  10. };
  11.  
  12. struct numar *prim = NULL;
  13. int nr_elem;
  14.  
  15. struct numar *creare(int val){
  16. struct numar *ptr = (struct numar*)malloc(sizeof(struct numar));
  17. if(NULL == ptr){
  18. printf("\nNu s-a putut crea nodul\n");
  19. return NULL;
  20. }
  21.  
  22. ptr->valoare = val;
  23. ptr->next = NULL;
  24. prim = ptr;
  25. nr_elem = 1;
  26. return ptr;
  27. }
  28.  
  29. //functie afisare stiva
  30.  
  31. void afisare_coada(){
  32. struct numar *ptr = prim;
  33. printf("\nInceput coada");
  34. while(ptr != NULL){
  35. printf("\n %d \n", ptr->valoare);
  36. ptr = ptr->next;
  37. }
  38. printf("\nSfarsit coada");
  39. }
  40.  
  41. //functie adaugare in stiva push
  42.  
  43. struct numar *push(val){
  44. struct numar *ptr = (struct numar*)malloc(sizeof(struct numar));
  45. ptr->valoare = val;
  46. ptr->next = NULL;
  47. if(NULL == prim){
  48. creare(val);
  49. }else{
  50. ptr->next = prim;
  51. prim = ptr;
  52. nr_elem++;
  53. }
  54. afisare_coada();
  55. return ptr;
  56. }
  57.  
  58. //functie pop
  59.  
  60. int pop(){
  61. struct numar *pop = prim;
  62. struct numar *temp = NULL;
  63. if(pop != NULL){
  64. prim = prim->next;
  65. }
  66. free(pop);
  67. pop = NULL;
  68. afisare_coada();
  69. return 1;
  70. }
  71.  
  72. //functie empty
  73.  
  74. int empty(){
  75. struct numar *ptr = prim;
  76. while(ptr != NULL){
  77. pop();
  78. afisare_coada();
  79. }
  80. return 1;
  81. }
  82.  
  83.  
  84. int main(){
  85. int i;
  86. for (i = 5; i>0; i--){
  87. push(i);
  88. }
  89. pop();
  90. getch();
  91. }

URL: http://ssm-iscri.ro

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.