C语言面试:Reverse Sentence, Reverse LinkedList

 

// Reverse the word order of a c-string
// for example:  "Avere is the best" --> "best the is Avere"

void reverse(char* begin, char *end) {
    char tmp;
    while(begin < end) { //begin end
        tmp = *begin;
        *begin++ = *end;
        *end-- = tmp;
    }
}
// "" -> ""
// "best" -> "best"
// "best world" -> "best world"
// " best world " -> " world best " ?????? [ tseb dlrow ]
// ""
// "a best" -> 
// str == NULL
void reverseSentence(char* str) 
{
    if(!str) return;
    char *begin = str; 
    char *s = str;
    while(*s) {
        s++;
        if(*s == '\0') {
            reverse(begin, s-1);
        } else if(*s == ' ') {
            reverse(begin, s-1); // erevA
            begin = s+1;
        }
    }
    // "erevA si eht tseb"
    reverse(str, s-1);
    // "best the is Avere"
}


// uint_32 data
typedef struct list_node{
    int val;
    struct list_node *next;
} s_list_node;

void insert(s_list_node *head, int data) {
    // lock
    s_list_node *h = head;
    if(!h) return; // unlock
    while(h->next) {
        h = h->next;
    }
    s_list_node *node = (s_list_node *)malloc(sizeof(s_list_node));
    node->val = data;
    h->next = node;
    // unlock
}

s_list_node *lookup(s_list_node *head, int target) {
    s_list_node *h = head;
    while(h) {
        if(h->val == target) return h;
        h = h->next;
    }
    return NULL;
}

// 1->2->3->4 => 4->3->2->1
void reverse(s_list_node **head) {
    s_list_node *prev = NULL;
    s_list_node *cur = *head;
    while(cur) {
        s_list_node *next = cur->next;
        cur->next = prev;
        prev = cur;
        cur = next;
    }
    *head = prev;
}

 

 

你可能感兴趣的:(C语言面试:Reverse Sentence, Reverse LinkedList)