华为机试第二篇

来源:互联网 发布:淘宝背景 编辑:程序博客网 时间:2024/05/24 03:00

一:能过键盘输入任意一个字符串序列,字符串可能包含多个子串,子串以空格分隔,请编写一个程序,自动分离出各个子串,并使用’,’将其分隔,并且在最后也补充一个’,’,并将子串存储。

如果输入”abc def ghi    d”,结果将是abc,def,gh,i,d

要求实现函数

Void DivideString(const char *pInputStr,long IinputLen,char *pOutputStr);

输入:pInputStr:输入字符串

  IinputLen:输入字符串的长度

输出:pOutputStr:输出字符串,字符串已开辟好,与输入字符串等长

注意:只需要完成该函数功能算法,中间不需要有任何IO的输入输出

示例:

#include<stdio.h>

#include<string.h>

void DivideString(const char *pInputStr,long IinputLen, char *OutputStr)

{

int cnt=0,i=0;//计数

bool flag=false;

while(pInputStr[i]==' ')//去掉前面的空格,要注意,前面可能有空格输入

i++;

for(;i<IinputLen;i++)

{

if(pInputStr[i]==' ')

{

flag=true;

continue;

}

if(flag)

{

flag=!flag;

OutputStr[cnt++]=',';

}

OutputStr[cnt++]=pInputStr[i];

}

OutputStr[cnt]='\0';

}

void main()

{

char sz[20];

char result[20];

gets(sz);

DivideString(sz,strlen(sz),result);

printf("%s\n",result);

}


总结:1、对于字符串处理,需要的就留下来,不需要的就continue掉;

           2、空格问题是一个很大的问题,字符串处理的时候,要考虑空格问题,以及ascii码有-127到128,所以要加

256再进行比较;


二:将输入的一个单向链表,逆序后输出链表中的值,链表定义如下:

Typdef struct tagListNode

{

Int value;

Struct tagListNode *next;

}ListNode;

要求实现函数

Void converse(ListNode **head);

输入:head:链表头结点,空间已经开僻好

输出:head:逆序后的链表头节点

返回:无

注意:只需要完成该函数的功能算法,中间不需要任何IO的输入输出。

#include<iostream>

using namespace std;

typedef struct tagListNode

{

int value;

struct tagListNode *next;

}ListNode;

//输入6个数,采用尾插法建立链表

ListNode * createList(ListNode *head)

{

ListNode *p;

if(!head)

{

head=(ListNode *)malloc(sizeof(ListNode));

cin>>head->value;

head->next=NULL;

}

p=head;

for(int i=0;i<5;i++)

{

ListNode *tmp=(ListNode *)malloc(sizeof(ListNode));

cin>>tmp->value;

tmp->next=NULL;

p->next=tmp;

p=tmp;

}

return head;

}

//题目要求的函数(还可以精简)

//精简方法首先将s=null,p=head,不需要判断只要一个while循环即可实现,思想一样

/*

While(p)

{

Q=p->next;

p->next=s;

p=q;

s=p;

}

*head=p;即可

*/

void converse(ListNode **head)

{

if(!*head|!((*head)->next))

return ;

ListNode *p=*head,*q=(*head)->next,*s;

p->next=NULL;

if(!(q->next)){

q->next=p;

*head=q;

return;

}

s=q->next;

while(s){

q->next=p;

p=q;

q=s;

s=s->next;

}

q->next=p;//最后一个要处理

*head=q;

}

void print(ListNode *head)

{

while(head)

{

cout<<head->value<<ends;

head=head->next;

}

cout<<endl;

}

int main()

{

ListNode *head=NULL;

head=createList(head);

print(head);

converse(&head);

print(head);

return 0;

}

三:将一个字符串中出现次数最少的字符删掉,并保证删除后的字符顺序不变,如果出现次数最少的字符有多种,则这几种字符都要删除,该字符串长度不会超过20个字符。

例如:源字符串为“abcdd”,删除后为“dd

#include<iostream>

#include<memory.h>

using namespace std;

char *deleteMin(char *InputSrc,int ILen)

{

int sz[26]={0};

int min=20,i;//最小出现次数

for(i=0;i<ILen;i++)

++sz[InputSrc[i]-'a'];

for(i=0;i<26;i++)

if(sz[i]<min&&sz[i]!=0)

min=sz[i];

for(int t=0;*(InputSrc+t);++t)

if(sz[InputSrc[t]-'a']==min)

{

memcpy(InputSrc+t,InputSrc+t+1,ILen-t);

--t;//因为跳过了一位

}

return InputSrc;

}

int main()

{

char src[]="abcddefg";

deleteMin(src,strlen(src));

cout<<src<<endl;

return 0;

}

0 0