两个面试题
来源:互联网 发布:jsp 图片存到数据库 编辑:程序博客网 时间:2024/04/29 09:57
1. 实现一个lite版的字符串替换函数
C/C++:
char *strreplace(char *str, const char *sub,const char *rep)
限制条件和要求如下:
1.其中str为原字符串,sub为待被替换的子串。为简单起见, 假定字符串sub和rep长度一样
2.直接对原字符串str进行修改并返回, 不得使用malloc/new开辟新的内存空间
3.不得使用任何库函数/API, 包括但不限于strlen, strstr, strcpy, 如需使用类似功能, 请自行实现
#include <iostream>#include <cstdlib>using namespace std;//此函数支持原字符串中有多个子串的情况,将分别替换//多个子字符串重叠将处理为替换后跳过已替换部分,如aaabcd, aa, xx运行结果为xxabcd而不是xxxbcdchar *strreplace(char *str, const char *sub, const char *rep){char *ret = str;while (*str != '\0'){int i = 0;for (; *(sub + i) != '\0'; i++){if (*(str + i) != *(sub + i)) break;}if (*(sub + i) == '\0'){for (int j = 0; *(rep + j) != '\0'; j++)*str++ = *(rep + j);}else str++;}return ret;}int main(){char a[] = "fuck you mother fucker";char b[] = "fuck";char c[] = "shit";char *d = strreplace(a, b, c);while (*d != '\0')cout << *d++;cout << endl;system("Pause");return 0;}
2. 假设有两个单链表A和B,不带头节点,且长度一样,示例如下:
A:1->2->3->4
B:a->b->c->d
请逆转交替合并两个链表,示例结果如下:
4->d->3->c->2->b->1->a
C/C++:
节点类型定义如下:
structNode {
struct Node *next;
...
}
函数定义如下:
Node*reverse_merge(Node *A, Node *B)
其中A、B分别是指向对应链表的第一个节点的指针
请直接修改原有链表的next指针完成该操作,并返回新链表的第一个节点的指针#include <iostream>#include <cstdlib>using namespace std;struct Node {struct Node *next;char data;};//C/C++实现Node *reverse_merge(Node *A, Node *B){//前两个if防御式编程if (A == NULL) return A;if (A->next == NULL){B->next = 0;A->next = B;return A;}Node *A1 = A->next;Node *B1 = B->next;Node *B2 = B1->next;B->next = 0;while (A1 != NULL){A->next = B;B1->next = A;A = A1;A1 = A1->next;B = B1;B1 = B2;//运行到修改链表最后节点时B2已为NULL,不可再取其nextif(B2!=NULL) B2 = B2->next;}A->next = B;return A;}Node *buildList(Node *A, char c){Node *ret = A;while (A->next != NULL)A = A->next;Node *p = (Node*)malloc(sizeof(Node));p->data = c;p->next = NULL;A->next = p;return ret;}int main(){Node *A = (Node*)malloc(sizeof(Node));Node *B = (Node*)malloc(sizeof(Node));A->data = '1';B->data = 'a';A->next = B->next = NULL;A = buildList(A, '2');A = buildList(A, '3');A = buildList(A, '4');//A = buildList(A, '5');//A = buildList(A, '6');//分隔符B = buildList(B, 'b');B = buildList(B, 'c');B = buildList(B, 'd');//B = buildList(B, 'e');//B = buildList(B, 'f');/*while (B != NULL){cout << B->data << " ";B = B->next;}*/Node *C = reverse_merge(A, B);while (C != NULL){cout << C->data << " ";C = C->next;}cout << endl;system("Pause");return 0;}
0 0
- 两个面试题
- 两个面试题
- 两个有趣的面试题
- 面试题之两个字符串
- 两个小的面试题
- 两个鸡蛋--一道Google面试题
- 两个面试题(atoi, lgn)
- 两个经典面试题的解法
- 面试题,进程中的两个fork
- 面试题(两个亿位数相乘)
- 两个月薪上万的.Net面试题
- 面试题整理-两个栈实现队列
- 两个关于a,b的面试题
- 面试题7 两个栈实现队列
- 面试题:比较两个集合是否相等?
- Java面试题之一对调两个数
- 让两个数进值互换 面试题
- 面试题:一个数组实现两个栈
- android参数含义
- python核心编程笔记(9)- 异常
- 黑马程序员——枚举
- 使用phantomjs对页面进行截图
- java中终止for循环的方式
- 两个面试题
- 笨有笨的好处
- 设计原则小记 3条
- ubuntu12.04下安装cmake-3.0.1
- 不同的选择,不同的生活
- Spring mvc 配置多视图 jsp freemarker velocity等
- Avoid hardcoding the debug mode; leaving it out allows debug and release builds to automatically a
- BIOS 内存分布图
- 初级经理人需要上的三个台阶