fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define COUNT_NODES 10
  4. typedef struct N
  5. {
  6. int val;
  7. struct N* next;
  8. }Node;
  9.  
  10. void addNode(Node** root, int val)
  11. {
  12. Node* newNode = malloc(sizeof(Node));
  13. newNode->val = val;
  14. newNode->next = *root;
  15. *root = newNode;
  16. }
  17.  
  18. /**
  19. Index starts from 0
  20. */
  21. void shiftNode(Node** rootNode, int nodeIndex, int shifts)
  22. {
  23. int i=1;
  24. Node *pNode, *temp, *root = *rootNode;
  25. if((shifts <= 0) || (nodeIndex < 0))
  26. {
  27. return;
  28. }
  29.  
  30. if(nodeIndex != 0)
  31. {
  32. for(i=1; i<nodeIndex; i++)
  33. {
  34. root = root->next;
  35. }
  36. pNode = root->next;
  37. root->next = pNode->next;
  38. }
  39. else
  40. {
  41. *rootNode = root->next;
  42. pNode = root;
  43. root->next = pNode->next;
  44. }
  45.  
  46. for(i=0; i<shifts; i++)
  47. {
  48. root = root->next;
  49. }
  50. temp=root->next;
  51. root->next = pNode;
  52. pNode->next=temp;
  53. }
  54.  
  55. void print(Node* root)
  56. {
  57. while(root)
  58. {
  59. printf("%d -> ", root->val);
  60. root = root->next;
  61. }
  62. printf("END\n");
  63. }
  64.  
  65. int main()
  66. {
  67. int i=0;
  68. Node* root = NULL;
  69. srand(1234);
  70. while(i<COUNT_NODES)
  71. {
  72. addNode(&root, rand());
  73. i++;
  74. }
  75. print(root);
  76. shiftNode(&root, 0, 2);
  77. print(root);
  78. return 0;
  79. }
  80.  
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
2058368053 -> 2048787572 -> 72282698 -> 1019879755 -> 1017450741 -> 1222702060 -> 1057886067 -> 961126155 -> 465566339 -> 479142414 -> END
2048787572 -> 72282698 -> 2058368053 -> 1019879755 -> 1017450741 -> 1222702060 -> 1057886067 -> 961126155 -> 465566339 -> 479142414 -> END