Advertisement
Guest User

Untitled

a guest
Jun 1st, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.60 KB | None | 0 0
  1. // given a list of integers and an integer key, write a function which
  2. // finds all the integers in the list that are smaller than the first element
  3. // and moves them to the beginning of the list.
  4.  
  5. // So if the original list is 10->55->66->4->X,
  6. // the list should be modified to be 4->10->55->66->X
  7.  
  8. // If the original list is 10->4->1->X
  9. // the list should be modified to be 4->1->10->X
  10.  
  11. // If the original list is 10->55->3->9->10->89->1->11->X,
  12. // the modified list would be 3->9->1->10->55->10->89->11->X
  13.  
  14. // If the original list is empty it should remain unmodified
  15.  
  16. // Constraints:
  17. // don't delete any nodes (i.e. do not call free())
  18. // don't create any new structs (i.e. do not call malloc())
  19. // the nodes that are smaller and moved to the front should remain in their original relative order
  20. // the nodes that are greater than or equal should remain in their original relative order
  21.  
  22. void partition (list sourceList) {
  23.  
  24. if (sourceList->head == NULL) {
  25. printf ("The list is empty.\n");
  26. } else if (sourceList->head->next == NULL) {
  27. printf("The list only contains 1 node.\n");
  28. } else {
  29. link prev = sourceList->head;
  30. link curr = sourceList->head->next;
  31. int nodeCounter = 0;
  32. int maxValue = sourceList->head->value;
  33. while (curr != NULL) {
  34. :wif (curr->value < maxValue){
  35. if (nodeCounter == 0) {
  36. prev->next = curr->next;
  37. curr->next = sourceList->head;
  38. sourceList->head = curr;
  39. if (prev->next == NULL) {
  40. curr = NULL;
  41. } else {
  42. curr = prev->next;
  43. }
  44. } else {
  45. int counter = 1;
  46. link inserter = sourceList->head;
  47. link inserterNext;
  48. while (counter < nodeCounter) {
  49.  
  50. inserterNext = inserter->next;
  51. }
  52. counter ++;
  53.  
  54. inserterNext = inserter->next;
  55. prev->next = curr->next;
  56. curr = inserterNext;
  57. inserterNext->next = curr;
  58.  
  59.  
  60. curr = prev->next;
  61. }
  62. nodeCounter ++;
  63. } else {
  64. prev = prev->next;
  65. curr = curr->next;
  66. }
  67. }
  68.  
  69. }
  70. }
  71. ~
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement