fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct Node Node;
  5.  
  6. typedef union Data {
  7. int value;
  8. Node* node;
  9. } Data;
  10.  
  11. struct Node {
  12. Data data;
  13. struct Node* next;
  14. };
  15.  
  16. Node* group (int* array, int len)
  17. {
  18. Node* head = (Node*) malloc(sizeof(Node));
  19. head->data.node = (Node*) malloc(sizeof(Node));
  20. head->next = NULL;
  21. Node* outer = head;
  22. Node* curr = head->data.node;
  23. curr->data.value = array[0];
  24. curr->next = NULL;
  25.  
  26. int i;
  27. int prev = array[0];
  28. for(i = 1; i < len; i++) {
  29. if(array[i] == prev) {
  30. curr->next = (Node*) malloc(sizeof(Node));
  31. curr = curr->next;
  32. curr->data.value = array[i];
  33. curr->next = NULL;
  34. } else {
  35. outer->next = (Node*) malloc(sizeof(Node));
  36. outer = outer->next;
  37. outer->data.node = (Node*) malloc(sizeof(Node));
  38. curr = outer->data.node;
  39. curr->data.value = array[i];
  40. curr->next = NULL;
  41. prev = array[i];
  42. }
  43. }
  44.  
  45. return head;
  46. }
  47.  
  48. void print_int_list(Node* head)
  49. {
  50. Node* curr = head;
  51. printf("[");
  52. while(curr->next != NULL) {
  53. printf("%d, ", curr->data.value);
  54. curr = curr->next;
  55. }
  56. printf("%d]", curr->data.value);
  57. }
  58.  
  59. void print_nested_list(Node* head)
  60. {
  61. Node* curr = head;
  62. printf("[");
  63. while(curr->next != NULL){
  64. print_int_list(curr->data.node);
  65. printf(", ");
  66. curr = curr->next;
  67. }
  68. print_int_list(head->data.node);
  69. printf("]\n");
  70. }
  71.  
  72. int main(void) {
  73.  
  74. int a[] = {1,1,1,2,2,1,2};
  75.  
  76. print_nested_list(group(a, 7));
  77.  
  78. return 0;
  79. }
Success #stdin #stdout 0s 2300KB
stdin
Standard input is empty
stdout
[[1, 1, 1], [2, 2], [1], [1, 1, 1]]