fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. typedef struct Node{
  6. int data;
  7. struct Node* next;
  8. } Node;
  9.  
  10. Node* createNode(int value){
  11. Node* newNode = (Node*)malloc(sizeof(Node));
  12. newNode -> data = value;
  13. newNode -> next = NULL;
  14. return newNode;
  15. }
  16.  
  17. // Node ** head: Truyền vào địa chỉ của con trỏ
  18. void insertAtBack(Node** head, int value){
  19. Node* newNode = createNode(value);
  20.  
  21. // Nếu linked list ban đầu là rỗng, thì thêm trực tiếp
  22. if(*head == NULL){
  23. *head = newNode;
  24. return;
  25. }
  26.  
  27. // Duyệt đến node cuối của Linked lis
  28. Node* current = *head;
  29. while(current -> next != NULL){
  30. current = current -> next;
  31. }
  32.  
  33. current -> next = newNode;
  34. return;
  35.  
  36. }
  37.  
  38. // **head: Địa chỉ của con trỏ head
  39. void insertAtK(Node** head, int value, int k){
  40. Node* newNode = createNode(value);
  41.  
  42. // Nếu k = 0, quay về thao tác thêm đầu
  43. if(k == 0){
  44. // Nếu danh sách liên kết hiện tại là rỗng
  45. if(*head == NULL){
  46. *head = newNode;
  47. return;
  48. }
  49. else{
  50. newNode -> next = *head;
  51. *head = newNode;
  52. return;
  53. }
  54. }
  55.  
  56. Node* current = *head;
  57. int countNode = 0;
  58. while(current -> next != NULL && countNode < k - 1){
  59. current = current -> next;
  60. countNode++;
  61. }
  62.  
  63. // Nếu node hiện tại là node cuối (quay về thao tác thêm cuối)
  64. if(current -> next == NULL){
  65. current -> next = newNode;
  66. }
  67. else{ // Nếu node hiện tại là node giữa (thực hiện 2 lần gán)
  68. newNode -> next = current -> next;
  69. current -> next = newNode;
  70. }
  71.  
  72. }
  73.  
  74. void printList(Node* head){
  75. Node* current = head;
  76. if(current == NULL){
  77. printf("EMPTY\n");
  78. return;
  79. }
  80.  
  81. while(current != NULL){
  82. printf("%d ", current -> data);
  83. current = current -> next;
  84. }
  85. printf("\n");
  86. }
  87.  
  88. int main() {
  89. int q;
  90. scanf("%d",&q);
  91.  
  92. // Linked list
  93. Node* head = NULL;
  94.  
  95. for(int i=1;i<=q;i++){
  96. char command[30];
  97. scanf("%s", command);
  98. if(strcmp(command, "INSERT") == 0){
  99. int k, value;
  100. scanf("%d %d",&k ,&value);
  101. insertAtK(&head, value, k);
  102. }
  103. else if(strcmp(command, "PUSH_BACK") == 0){
  104. int value;
  105. scanf("%d",&value);
  106. insertAtBack(&head, value);
  107. }
  108. else if(strcmp(command, "PRINT") == 0){
  109. printList(head);
  110. }
  111. }
  112. return 0;
  113. }
  114.  
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Standard output is empty