标签:
对字符串“this is very good”进行翻转,即“good very is this”。注意每一个单词仍是正序
思路:
1.字符串的翻转的问题。能够使用栈实现。
2.先把全部字符翻转,然后对再对某一个单词翻转,终于实现题目要求。
C语言代码例如以下:
先把简单的栈实现列出来:
#ifndef dataStruct_myStack_h #define dataStruct_myStack_h #define kStacksize 100 typedef struct{ void* entity[kStacksize]; int top; }myStack; myStack* initStack(); void push(myStack* s,void* p); void* pop(myStack* s); void freeStack(myStack* s); #endif
#include <stdlib.h> #include "myStack.h" // myStack* initStack(){ myStack* s = (myStack*)malloc(sizeof(myStack)); memset(s->entity,0,sizeof(kStacksize)); s->top = -1; return s; } // void push(myStack* s,void* p){ if(s->top < kStacksize-1){ s->entity[++s->top] = p; } } // void* pop(myStack* s){ if (s->top>=0 && s->top < kStacksize) { return s->entity[s->top--]; } return NULL; } // void freeStack(myStack* s){ free(s); }
int main { //0.输出原始字符串 char* str = "this is very good";printf("%s\n",str); char* reversal= (char*)calloc(1, 100); char* result= (char*)calloc(1, 100); int length=0; //1.翻转全部字符串 reverString(str,strlen(str),reversal); printf("%s\n",reversal); //2.翻转单词 char* index = reversal; char* reversalPtr = reversal; char* resultPtr = result; while (*index) { if (*index ==' ') { reverString(reversalPtr,length,resultPtr); reversalPtr= index+1 ; resultPtr += length; *(resultPtr++) = ' '; length = 0; } else { length++; } index ++; } //3.最后一个单词。翻转一下。 reverString(reversalPtr,length,resultPtr); printf("%s",result); //4.清理数据 free(reversal); reversalPtr=NULL; free(result); result=NULL; } void reverString(char* str,int length,char*buffer){ if (length<=0) { return; } myStack * stack = initStack(); int i=0; while (i<length) { push(stack,str); str++; i++; } //1.总体翻转过来 char* tmp; while (tmp =(char*)pop(stack)) { *buffer = *tmp; buffer++; } freeStack(stack); }
this is very good
doog yrev si siht
good very is this
标签:
原文地址:http://www.cnblogs.com/lcchuguo/p/5181875.html