Tag: Stack string flip
Flip the string "this is very good", that is, "Good very is this ";Note that each word is still in the forward order.
Ideas:
1. stack implementation can be used to flip strings.
2. Flip all characters first, and then flip a word to meet the question requirements.
The C language code is as follows:
First, list the simple stack implementation:
# Ifndef 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 );}
Specific call.
Int main {// 0. output the original string 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. flip all strings reverstring (STR, strlen (STR), reversal); printf ("% s \ n", reversal); // 2. flip the word char * Index = reversal; char * reversalptr = reversal; char * resultptr = result; while (* index) {If (* Index = '') {reverstring (reversalptr, length, res Ultptr); reversalptr = index + 1; resultptr + = length; * (resultptr ++) = ''; length = 0 ;}else {length ++ ;} index ++;} // 3. flip the last word. Reverstring (reversalptr, length, resultptr); printf ("% s", result); // 4. clear data free (reversal); reversalptr = NULL; free (resultptr); resultptr = 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 );}
The output result is:
This is very good
Doog yrev Si siht
Good very is this