fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. using ll = long long;
  5.  
  6. //Them, xoa
  7. struct node{
  8. int data;
  9. node *next;
  10. };
  11.  
  12. node* taoNode(int x){
  13. node *newNode = new node;
  14. newNode->data = x;
  15. newNode->next = NULL;
  16. return newNode;
  17. }
  18.  
  19. void duyet(node *head){
  20. while(head != NULL){
  21. cout << head->data << " ";
  22. head = head->next;
  23. }
  24. cout << endl;
  25. }
  26.  
  27. int dem(node *head){
  28. int cnt = 0;
  29. while(head != NULL){
  30. ++cnt;
  31. head = head->next;
  32. }
  33. return cnt;
  34. }
  35.  
  36. //pass by value
  37. void themdau(node *&head, int x){
  38. node *moi = taoNode(x);
  39. moi->next = head;
  40. head = moi;
  41. }
  42.  
  43.  
  44. void themcuoi(node *&head, int x){
  45. node *moi = taoNode(x);
  46. //di den node cuoi trong dslk
  47. node *tmp = head; // dung de duyet
  48. if(head == NULL){
  49. head = moi; return;
  50. }
  51. while(tmp->next != NULL){
  52. tmp = tmp->next;
  53. }
  54. //tmp : node cuoi
  55. tmp->next = moi;
  56. }
  57.  
  58. //Muon them vao vi tri thu k => den duoc node truoc no : k - 1
  59. void themgiua(node *&head, int x, int k){
  60. int n = dem(head);
  61. if(k < 1 || k > n + 1){
  62. return;
  63. }
  64. if(k == 1){
  65. themdau(head, x); return;
  66. }
  67. node *moi = taoNode(x);
  68. node *tmp = head;
  69. for(int i = 1; i <= k - 2; i++){
  70. tmp = tmp->next;
  71. }
  72. moi->next = tmp->next; // k
  73. tmp->next = moi;
  74. }
  75.  
  76. int main(){
  77. node *head = NULL;
  78. for(int i = 1; i <= 10; i++){
  79. themcuoi(head, i);
  80. }
  81. themgiua(head, 100, 11);
  82. duyet(head);
  83. }
Success #stdin #stdout 0.01s 5304KB
stdin
Standard input is empty
stdout
1 2 3 4 5 6 7 8 9 10 100