4 ms·
Instead of using a while loop to iterate through a linked list, consider using a for loop. Node * iter; for (iter=root; iter != NULL; iter=iter->next) {
by Locke1689 16y ago
Instead of using a while loop to iterate through a linked list, consider using a for loop.
Node * iter;
for (iter=root; iter != NULL; iter=iter->next) {
/* iter->object; */
}
A concise implementation of strlen
size_t strlen(char * str) {
char * cur;
for(cur=str; *cur; ++cur);
return (cur-str);
}
Reverse a string in-place.
void reverse(char * str) {
char *i,*j, tmp;
for (i=str, j=(str+strlen(str)-1); i < j; ++i,++j) {
tmp = *i;
*i = *j;
*j = tmp;
}
- mrb 16y agoYou have a bug in strlen: for(cur=str; cur; ++cur); should be: for(cur=str; *cur; ++cur);
- Locke1689 16y agoRight you are. Wrote all those in the comment block. Fixed in an edit.
- phsoftnet 16y agosize_t strlen(char *s) { size_t i = 0; while(*s++) i++; return i; }
- visualphoenix 16y agoShouldn't that be --j in your reverse function? Anyhow, when asked to write those on a blackboard, I typically do this: size_t strlen(char* start) { char* end=start; while(*end) ++end; return (end-start); } and void reverse(char* i) { char* j=(i+strlen(i)-1); for (; i < j; ++i,--j) { *i ^= *j; *j ^= *i; *i ^= *j; }
- Locke1689 16y agoYup, --j. Also, the XOR version probably isn't worth the complexity.
- visualphoenix 16y agoTrue in practice, but on a blackboard during an interview, it obviates the need to recode for the follow-up "now reverse the string in place" request.
- sfgfdhgfdshdhhd 16y agovoid strcpy(char s1, char s2) { while((s1++) = (s2++)); }