c - 使用链表中的堆栈反转C中的字符串
问题描述
我正在尝试使用堆栈反转给定的字符串。我正在使用链表,因为与数组相比,它占用的内存更少。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define M 100
struct Stack{
char ele;
struct Stack *next;
};
struct Stack* next_node(char element){
struct Stack *node=(struct Stack *)malloc(sizeof(struct Stack));
node->ele=element;
node->next=NULL;
return node;
}
int isEmpty(struct Stack *node){
return node==NULL;
}
void push(struct Stack **node, char element){
struct Stack *temp=next_node(element);
temp->next=*node;
*node=temp;
}
char pop(struct Stack **node){
if(isEmpty(*node)){
return 'a';
}
struct Stack *temp=*node;
*node=(*node)->next;
free(temp);
}
void rev(char str[]){
int i;
int n=strlen(str);
struct Stack *s=(struct Stack *)malloc(sizeof(struct Stack));
for(i=0;i<n;i++)
push(&s, str[i]);
for(i=0;i<n;i++)
str[i]=pop(&s);
printf("The reversed string is: %s\n", str);
}
int main()
{
char string[M], op[1];
do{
printf("Enter the string to be reversed: ");
scanf("%s", string);
rev(string);
printf("Do you want to go again?(Y/N): ");
scanf("%s", op);
}while(op[0]=='Y');
}
但是,我没有得到任何输出,它只是说,“反转的字符串是:”
我通过替换尝试了稍微不同的代码
node->ele=element;
和
strcpy(node->ele, element);
但这给了我一个警告,上面写着:
warning: passing argument 1 of 'strcpy' makes pointer from integer without a cast
我无法理解为什么会发生这样的事情。任何帮助表示赞赏!:-)
解决方案
你可以完全跳过堆栈,做一些更简单、更快的事情,如下所示:
void rev(char str[])
{
int i;
int n = strlen(str);
for(i=0; i<n/2; i++) {
char tempChar = str[i];
str[i] = str[n-i-1];
str[n-i-1] = tempChar;
}
printf("The reversed string is: %s\n", str);
}
基本上,只需遍历字符串的一半(如果长度为奇数,则不包括中间字符),并从字符串的左半部分和右半部分交换字符。
推荐阅读
- python - 将整数列表添加到整数列表中
- java - SQLITE_ERROR SQL 错误或缺少数据库(“语句”附近:语法错误)
- powershell - 在 Powershell 中过滤 XML 数据并以相同的 XML 格式保存到目标文件夹
- python-3.x - Web 以重复的时间间隔抓取 http 文本文件页面
- django - Django 中的已验证用户
- webpack - 编写库时的模块名称 Webpack 和 vue-cli
- python - ValueError: no enough values to unpack (expected 2, got 1), Splitting string into two parts with split() didn't work
- php - 我需要使用另一个页面上的数据
- angular - 使用量角器在 Firefox 上下载 PDF 文件不起作用
- java-8 - 如何阅读 Jave 8 元空间转储