嵌入式软件工程师C语言经典笔试2

1. 使用宏定义swap函数,不使用中间变量

#define swap(x,y) {(x) = (x) + (y);(y) = (x) - (y);(x) = (x) - (y)}
View Code

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--;
    }
    
}
View Code

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;
    }
}
View Code

  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;
}
View Code

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;
}
View Code

5. 判断一个数是否是2的次幂

inline int Is2exp(int i)
{
    return (i&(i-1))?0:1);
}
View Code

 

posted @ 2019-03-16 11:20  三七鸽  阅读(280)  评论(0编辑  收藏  举报