fork download
  1. #include <stdio.h>
  2. #include <malloc.h>
  3.  
  4. typedef struct elem{
  5. char name[50];
  6. int code;
  7. } Element;
  8.  
  9. typedef struct node{
  10. Element elem;
  11. struct node*next;
  12. } Stack;
  13.  
  14. void push(Stack**head, Element el){
  15. Stack *q = (Stack*)malloc(sizeof(Stack));
  16. q->elem = el;
  17. q->next = *head;
  18. *head = q;
  19. }
  20.  
  21. void pop(Stack**head){
  22. Stack*q = *head;
  23. if(isEmpty(*head)) return;
  24. *head = (*head)->next;
  25. free(q);
  26. }
  27.  
  28. Element top(Stack**head) {
  29. Stack*q = *head;
  30. Element el = (*head)->elem;
  31. *head = (*head)->next;
  32. free(q);
  33. return el;
  34. }
  35.  
  36. int isEmpty(Stack*head) {
  37. if(head == NULL) return 1;
  38. else
  39. return 0;
  40. }
  41.  
  42. void create(Stack**head) {
  43. Stack*q;
  44. Element e;
  45. *head = NULL;
  46. int n, i;
  47. printf("%s", "How many elements do you want N = ");
  48. scanf("%d", &n);
  49. for(i = 0; i < n; ++i) {
  50. q = (Stack*)malloc(sizeof(Stack));
  51. printf("Element#%d:\n", i + 1);
  52. printf("%s:", "Name=");
  53. //scanf("%s",q->elem.name);
  54. printf("%s:", "Code=");
  55. //scanf("%d",&q->elem.code);
  56. scanf("%s %d",e.name, &e.code);
  57. q->elem = e;
  58. q->next = *head;
  59. *head = q;
  60. }
  61. }
  62.  
  63. void write(Stack*head) {
  64. while(head) {
  65. printf("(%s, %d)\n", head->elem.name, head->elem.code);
  66. head = head->next;
  67. }
  68. }
  69.  
  70. void strcp(char str1[50],char str2[]) {
  71. int i = 0;
  72. while(str2[i]!='\0'){
  73. str1[i] = str2[i];
  74. i++;
  75. }
  76. str1[i] = '\0';
  77. }
  78.  
  79. int main(int argc, char const *argv[]) {
  80. Stack*head;
  81. create(&head);
  82. write(head);
  83. Element el = top(&head);
  84. printf("(%s,%d)\n", el.name, el.code);
  85. strcp(el.name,"adrian");
  86. el.code = 1234;
  87. push(&head,el);
  88. write(head);
  89. return 0;
  90. }
Success #stdin #stdout 0.01s 5548KB
stdin
3
May 123
Ann 321
Campanera 901
stdout
How many elements do you want N = Element#1:
Name=:Code=:Element#2:
Name=:Code=:Element#3:
Name=:Code=:(Campanera, 901)
(Ann, 321)
(May, 123)
(Campanera,901)
(adrian, 1234)
(Ann, 321)
(May, 123)