I this post we have provided part 1 of the C programs most commonly asked in interview along with answers. We recommend you to try to answer the questions, before referring to the given answer. If you find any mistake or a better alternate solution we are happy to see your suggestions and comments
1. Write function to reverse linked list
void Reverse(Node_t **head) { Node_t *cur = *head; Node_t *prev = NULL; Node_t *next = NULL; while(cur) { next = cur->next; cur->next = prev; prev = cur; cur = next; } *head = prev; return; } Reverse(&head);
2. Write function to reverse linked list using recursion
Node_t * Reverse(Node_t *head, Node_t *prev) { Node_t *last = 0; if(0 == head) return prev; last = Reverse(head->next, head); head->next = prev; return last; }
3. Write a function to insert in a doubly linked list
void InsertAfter(Node_t *cur, Node_t *new) { new->next = cur->next; cur->next = new; new->prev = cur; new->next->prev = new; }
4. Write the implementation of strlen() function
size_t strlen(const char *str) { size_t len = 0; while(str[len++]); return len; }
5. Write the implementation of strcpy() function
char * strcpy(char *dst, const char *src) { char *itr = dst; while(*itr++ = *src++); return dst; }
6. Write the implmentation of strncpy() function
char * strncpy(char *dst, const char *src, size_t len) { char *itr = dst; while(len-- && (*itr++ = *src++)); return dst; }
7. Write the implementation of strcat() fucntion
char * strcat(char *dst, const char *src) { char *end = dst; while(*end) end++; while(*end++ = *src++); return dst; }
8. Write the implementation of strncat() function
char * strncat(char *dst, const char *src, size_t len) { char *end = dst; while(*end) end++; while(*end++ = *src++ && len--) *end = 0; return dst; }
9. Write the implementation of strchr() function
char * strchr(char *src, const char ch) { while(*src) { if(*src == ch) return src; else src++; } return NULL; }
10. Write the implementation of strrchr() function
char * strrchr(char *str, const char ch) { char *end = str; while(*end) end++; while(*--end) if(*end == ch) return end; return NULL; }