Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- struct c_list{
- char c; // The character
- int n; // how many times it's been seen before.
- struct c_list* next; // pointer to the next node
- };
- void add(struct c_list* node, char c){
- if (node->c == c){
- // Case one: we find our node
- node->n++; // increase its count
- } else if (node->next){
- // Case two: we didn't find our node, but there are more
- add(node->next, c); // add c to the next node
- } else {
- // Case three: we've reached the end
- node->next = (struct c_list*)malloc(sizeof(struct c_list));
- node->next->c = c;
- node->next->n = 1;
- node->next->next = 0;
- }
- }
- void traverse_and_print(struct c_list* node){
- if (!node) return; // termination condition
- printf("%c-%d\n", node->c, node->n);
- traverse_and_print(node->next);
- // After recursion, we free the memory from right to left
- // we can implement a simple stack check here to
- // make sure that we're not freeing from the stack,
- // but that seems unnecessary.
- /*
- void* stackptr = &node;
- if (node < stackptr-0x1000)
- */
- free(node);
- }
- int main(int argc, char** argv){
- struct c_list parent = {(char)EOF, 0, 0}; // sentinel header
- for(;argc>1;argc--){
- char *arg = *++argv; // argv[0] is filename
- while (*arg){ // C strings are null terminated
- char c = *arg++;
- add(&parent, c); // add the char into the LL
- }
- }
- traverse_and_print(parent.next); // Print the contents of the LL
- return 0;
- }
Add Comment
Please, Sign In to add comment