Showing posts with label C programming. Show all posts
Showing posts with label C programming. Show all posts

Friday, August 19, 2011

String reversal with words in tact!!

I am on a freaking C programming spirit for past two days!! I feel like coding all the way!!

Problem statement
===============================================

Reverse a string with words, with words intact.
Example will make it explain better 

Input string:: "I am a programming freak!"
Output :: "freak! programming a am I" 



Another -- "I use Mac book" i.e. "book Mac use I"
===============================================
Here is my working Solution!!
===============================================

<pre class="prettyprint">
int main()
{
    char *orig_str = NULL;
    char *rev_str;
    char str[80]; //This is a limitation right now
    char delims[] = " ";
    int orig_len,len =0,slen =0;

    printf("Please enter the string you want to reverse in words\n");
    fgets(str, 80, stdin); //fgets has ugly trailing '\n' too
    len = strlen(str);
    
    if (str[len-1] == '\n')
        str[len-1] = '\0';

    orig_len = len = strlen(str); //new str len with out \n

    rev_str = (char *)malloc(len+1);
    rev_str[len] = '\0';

    orig_str = strtok(str, delims);
    while (orig_str != NULL) {
            slen = strlen(orig_str);
    
            //this to prevent adding space for the first word
            //in orig_str which will be the last in rev_str
            if (len < orig_len)
               strncpy(&rev_str[len]," ",1);

            len = len - slen;
            strncpy(&rev_str[len],orig_str,slen);

            len--;  // for space added to the rev_str

            orig_str = strtok(NULL,delims);
    }
    printf("\nString reversed in words is :\"%s\"\n",rev_str);
    free(rev_str);
}
 

Cyclic Sorted List

Problem from : http://programmingpraxis.com/
=====================================================
Given a node from a cyclic linked list which has been sorted,
write a function to insert a value into the list such that it
remains a cyclic sorted list. The given node can be any single node
in the list
=====================================================

This problem got my attention as I am kinda fond of lists.
I worked out my logic, this way

1) If node passed in is NULL, => no elements so far in list.
create a new node and back point to itself
2) first and last elements of list i.e. highest or lowest (could be equal too)
It should be inserted at the end or beginning (both same as it's cyclic list)
3) Any other element to be inserted in the middle (could be equal to one of the elements)
find prev->elem <= elem_to_insert <= next->elem

Tricky part I find here is, for cases (2) and (3), we might have to get to the starting point of the list. This is because we are given some random node as input, not the head node. So, element we need to insert might just happen go before the input node. So, we start from input node and make a loop through all the nodes until we hit the same input node again.

After going over and going over again to crisp it(;), here is my solution!

=====================================================

<pre class="prettyprint">
 
typedef struct node_ {
    int x;
    node *next;
} node_t;


node_t* create_node(node_t *node_next,int to_insert) {
    node_new = malloc(sizeof(struct node_));
    if (node_new != NULL) {
        node_new->x = to_insert;
        node_new->next = node_next;
    } else {
         printf("\n Malloc failed. \n");
         exit(0);
    }   
    return node_new;
}

node_t *insert_node(node_t *curr, int i) {
    node_t *node_new=NULL, *prev=NULL,*given_node;
    given_node = curr;
    if (curr == NULL) {
        //empty list
        node_new = create_node(curr,to_insert);
        node_new->next = node_new; //point to itself
    } else { //not an empty list
        do {
            prev = curr;
            curr = curr->next;

            /* insert at beginning or end - highest or lowest */
            if ((prev->x > curr->x)  &&
                 (i >= prev->x || i <= curr->x))
                 break;

            /* insert in between */
            if ( i >= prev->x && i <= curr->x)
                break;
        }  while (curr != given_node);

        node_new = create_node(curr,i);
    }
    return node_new;
}