标签:
1. 求一个数的二进制中的1的个数。
int func(int x) { int count = 0; while (x) { count++; x = x& (x - 1); } return count; }
2. 已知strcpy的函数原型:char *strcpy(char *strDest, const char *strSrc)其中strDest 是目的字符串,strSrc 是源字符串。不调用C++/C 的字符串库函数,请编写函数 strcpy。
int _tmain(int argc, _TCHAR* argv[]) { const char *srcStr = "This is a source string."; //char *desStr = (char *)malloc(sizeof(srcStr)); // Or below: char *desStr = (char *)malloc(sizeof(char)* strlen(srcStr) + 1); myStrcpy(desStr, srcStr); printf("Copy result: %s", desStr); } char *myStrcpy(char *strDest, const char *strSrc) { if (strSrc == NULL || strDest == NULL) { return NULL; } if (strDest == strSrc) { return strDest; } char *strDestStart = strDest; while (*strDest !=‘\0‘) { *strDest++ = *strSrc++; } return strDestStart; }
3. 链表题:
一个链表的结点结构
struct Node { int data ; Node *next ; }; typedef struct Node Node ;
(1)已知链表的头结点head,写一个函数把这个链表逆序
思路: 用三个指针p0,p1,p2,从头到尾依次遍历并反转结点
int _tmain(int argc, _TCHAR* argv[]) { int linkedListLength = 5; Node *myList = new Node(); Node *p = myList; printf("Original linked list is:"); for (int i = 0; i < linkedListLength; i++) { Node *node = new Node(); node->data = i; printf(" %d", i); p->next = node; p = node; } Node *reversedMyList = ReverseLinkedList(myList); printf("\r\nReversed linked list is:"); Node *r = reversedMyList; while (r->next != NULL) { printf(" %d", r->data); r = r->next; } } Node *ReverseLinkedList(Node *head) { // NULL if (head == NULL) { return NULL; } // One node only. if (head->next == NULL) { return head; } // Two or more than two nodes. Node *p0 = head; Node *p1 = p0->next; Node *p2 = p1->next; //p2 maybe null; p0->next = NULL; while (p2 != NULL) { p1->next = p0; p0 = p1; p1 = p2; p2 = p2->next; } p1->next = p0; return p1; }
标签:
原文地址:http://www.cnblogs.com/fdyang/p/4387663.html