华为上机题汇总(十一)
注:编译环境为Visual Studio 2012,答案仅供参考。
目录
第五十一题
51.子串分离
题目描述:
通过键盘输入任意一个字符串序列,字符串可能包含多个子串,子串以空格分隔。请编写一
个程序,自动分离出各个子串,并使用’,’将其分隔,并且在最后也补充一个’,’并将子
串存储。
如果输入“abc def gh i d”,结果将是abc,def,gh,i,d,
要求实现函数:
void DivideString(const char *pInputStr, long lInputLen, char *pOutputStr);
【输入】 pInputStr: 输入字符串
lInputLen: 输入字符串长度
【输出】 pOutputStr: 输出字符串,空间已经开辟好,与输入字符串等长;
#include <iostream>
using namespace std;
void DivideString(const char *pInputStr, long lInputLen, char *pOutputStr){
while (*pInputStr != '\0')
{
if (*pInputStr == ' ')
{
pInputStr++;
continue;
}
while (*pInputStr != '\0' && *pInputStr != ' ')
{
*pOutputStr++ = *pInputStr++;
}
*pOutputStr++ = ',';
}
*pOutputStr = '\0';
}
int main()
{
char input[100],output[100];
cin.getline(input,100);
DivideString(input,strlen(input),output);
cout << output << endl;
return 0;
}
第五十二题
52.链表翻转。
给出一个链表和一个数k,比如链表1→2→3→4→5→6,k=2,则翻转后2→1→4→3→6→5,若k=3,翻转后3→2→1→6→5→4,若k=4,翻转后4→3→2→1→5→6,用程序实现
思想:采用遍历链表,分成length/k组,对每组进行逆转,逆转的同时要将逆转后的尾和头连接起来
#include <iostream>
using namespace std;
bool invalidInput = false;
struct LNode{
int value;
LNode* next;
};
LNode* reverKNodes(LNode *begin, int k){
LNode *head = begin->next, *front = head, *p = front->next;
for (int i = 0; i < k-1; i++)
{
LNode *after = p->next;
p->next = front;
front = p;
p = after;
}
begin->next = front;
head->next = p;
return head;
}
LNode* reverseList(LNode *phead, int k){
if (!phead || k < 0)
{
invalidInput = true;
return phead;
}
LNode *p = phead;
bool end = false;