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而不是xxxbcd
char *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,不可再取其next
if(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;
}