Guest User

Untitled

a guest
Jan 22nd, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct c_list{
  5. char c; // The character
  6. int n; // how many times it's been seen before.
  7. struct c_list* next; // pointer to the next node
  8. };
  9.  
  10. void add(struct c_list* node, char c){
  11. if (node->c == c){
  12. // Case one: we find our node
  13. node->n++; // increase its count
  14. } else if (node->next){
  15. // Case two: we didn't find our node, but there are more
  16. add(node->next, c); // add c to the next node
  17. } else {
  18. // Case three: we've reached the end
  19. node->next = (struct c_list*)malloc(sizeof(struct c_list));
  20. node->next->c = c;
  21. node->next->n = 1;
  22. node->next->next = 0;
  23. }
  24. }
  25.  
  26. void traverse_and_print(struct c_list* node){
  27. if (!node) return; // termination condition
  28. printf("%c-%d\n", node->c, node->n);
  29. traverse_and_print(node->next);
  30. // After recursion, we free the memory from right to left
  31. // we can implement a simple stack check here to
  32. // make sure that we're not freeing from the stack,
  33. // but that seems unnecessary.
  34. /*
  35. void* stackptr = &node;
  36. if (node < stackptr-0x1000)
  37. */
  38. free(node);
  39. }
  40.  
  41. int main(int argc, char** argv){
  42. struct c_list parent = {(char)EOF, 0, 0}; // sentinel header
  43. for(;argc>1;argc--){
  44. char *arg = *++argv; // argv[0] is filename
  45. while (*arg){ // C strings are null terminated
  46. char c = *arg++;
  47. add(&parent, c); // add the char into the LL
  48. }
  49. }
  50. traverse_and_print(parent.next); // Print the contents of the LL
  51. return 0;
  52. }
Add Comment
Please, Sign In to add comment