题目:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
注:该题目已有大神实现了,地址为 https://blog.csdn.net/lanxu_yy/article/details/38827845,但使用的是C++语言。
思路:大体为使用链表栈进行先进后出的操作方式。
直接上代码:
/*
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node
{
char *dest;
struct node *Next;
};
typedef struct node Node;
// char * reverse(Node *node, char *dest, int begin, int end)
// {
// int i = 0;
// int j = 0;
// for(i = 0, j = 0; i < end; i++){
// if(dest[i] == ' '){
// Node *temp = (Node *)malloc(sizeof(Node));
// node->Next = temp;
// temp->dest = (char *)malloc(i - j + 1);
// printf("i = %d, j = %d\n", i, j);
// printf("dest = %s\n", &dest[j]);
// strncpy(temp->dest, &dest[j], i-j);
// printf("temp->dest = %s\n", temp->dest);
// j = i+1;
// node = node->Next;
// }
// }
// if(dest[i] != ' '){
// Node *temp = (Node *)malloc(sizeof(Node));
// node->Next = temp;
// temp->dest = (char *)malloc(i - j + 1);
// strncpy(temp->dest, &dest[j], i-j);
// }
// }
Node * reverse(Node *node, char *dest, int begin, int end)
{
int i = 0;
int j = 0;
for(i = 0, j = 0; i < end; i++){
if(dest[i] == ' '){
Node *temp = (Node *)malloc(sizeof(Node));
temp->Next = node; //关键代码:入栈操作
temp->dest = (char *)malloc(i - j + 1);
// printf("i = %d, j = %d\n", i, j);
// printf("dest = %s\n", &dest[j]);
strncpy(temp->dest, &dest[j], i-j);
// printf("temp->dest = %s\n", temp->dest);
j = i+1;
node = temp;
// printf("temp = %p\n", temp);
// printf("node = %p\n", node);
}
}
if(dest[i] != ' '){
Node *temp = (Node *)malloc(sizeof(Node));
temp->Next = node;
temp->dest = (char *)malloc(i - j + 1);
strncpy(temp->dest, &dest[j], i-j);
// printf("temp->dest = %s\n", temp->dest);
node = temp;
// printf("node2 = %p\n", node);
return node;
}
}
int main(int argc, char const *argv[])
{
char *string = "the sky is blue";
// strcat(string, " ");
printf("%s\n", string);
int length = strlen(string);
// printf("length = %d\n", length);
Node *top = (Node *)malloc(sizeof(Node));
Node *temp1 = reverse(top, string, 0, length);
// printf("top = %p\n", top);
char * destStr = (char *)malloc(length);
int index = 0;
while(temp1->Next != NULL){
// printf("%s\n", temp1->dest);
strncpy(destStr + index, temp1->dest, strlen(temp1->dest));
// printf("index = %d\n", index);
index += strlen(temp1->dest);
strncpy(destStr + index, " ", 1);
index += 1;
temp1 = temp1->Next;
}
char * point = destStr;
printf("dest = %s\n", destStr);
// for (int i = 0; i < length; ++i)
// {
// printf("point[%d] = %d, %c\n", i, point[i], point[i]);
// /* code */
// }
return 0;
}
可直接运行。
网友评论