嵌入式软件工程师C语言经典笔试2
1. 使用宏定义swap函数,不使用中间变量
#define swap(x,y) {(x) = (x) + (y);(y) = (x) - (y);(x) = (x) - (y)}
2. 实现字符串的反转
#define swap(x,y) {(x) = (x) + (y);(y) = (x) - (y);(x) = (x) - (y);} void reverse(char *string) { int len = strlen(string); char *begin = string; char *end = string + len - 1; while (begin < end) { swap(*begin,*end); begin++; end--; } }
3. 实现单链表的反转
3.1 方式一列表头不反转
void reverse_node(struct node *pHeader) { struct node *p = pHeader->pNext; struct node *pbackup = NULL; if(NULL == pHeader || NULL == p) { printf("node should more one\n"); return; } while(NULL != p) { pbackup = p->pNext; if(pHeader->pNext == p) { p->pNext = NULL; } else { p->pNext = pHeader->pNext; pHeader->pNext = p; } p = pbackup; } }
3.2 方式二列表头也反转
struct node * reverse(struct node *pHeader) { if (pHeader== NULL || pHeader-> Next == NULL) { return pHeader; } struct node *p = pHeader-> Next; struct node *pNewHeader = reverse(p); p -> Next = pHeader; pHeader->Next = NULL; return pNewHeader; }
4. 计算二叉树的高度
typedef struct BinTreeNode { int data; struct BinTreeNode *lchild; struct BinTreeNode *rchild; }*BSTree int depth(BSTree T) { if(!T) { return 0; } int d1=depth(T->lchild); int d2=depth(T->rchild); return (d1>d2?d1:d2)+1; }
5. 判断一个数是否是2的次幂
inline int Is2exp(int i) { return (i&(i-1))?0:1); }