我被給了這個問題,我需要爲它創建一個代碼。因此,我們有一個由用戶輸入的字符串,然後代碼需要檢查句子是否是迴文句(句子中間的對稱詞應該是相同的,但我們應該使用堆棧來實現。 我熟悉函數pop()和push()(甚至認爲我沒有在下面使用它們)。我到現在爲止的想法是,我接收字符串並從這些字符串中創建一堆字,然後使用該字符串檢查句子是迴文。我現在堅持,我真的不能想別的,幫助將非常感激。C中的單詞棧(句子迴文)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stack
{
char s[30];
struct stack *next;
};
typedef struct stack STACK;
struct top
{
int num;
struct stack *top;
};
typedef struct top TOP;
void create_stack(TOP *s, char str[1000])
{
char temp1[30];
int i=0, j=0;
STACK *temp;
temp=(STACK*)malloc(1*sizeof(STACK));
while(1)
{
if(str[i]!=' ' && str[i]!='\0')
{
temp1[j]=str[i];
j++;
}
else
{
temp1[j]='\0';
strcpy(temp->s,temp1);
printf("%s\n", temp->s);
if(s->top==NULL)
{
s->top=temp;
s->num=1;
}
else
{
temp->next=s->top;
s->top=temp;
s->num++;
}
j=0;
}
if(str[i]=='\0')
{
break;
}
i++;
}
}
void move_cursor(STACK *cursor, int pos)
{
while (pos!=0)
{
cursor=cursor->next;
pos--;
}
}
void compare(TOP *s)
{
STACK *cursor1, *cursor2;
cursor1=s->top;
cursor2=s->top;
int cursor_move1, cursor_move2, i=0, check=1;
if(s->num%2==0)
{
cursor_move1=s->num/2;
cursor_move2=(s->num/2)+1;
while (i!=cursor_move1)
{
cursor1=s->top;
cursor2=s->top;
move_cursor(cursor1, i);
move_cursor(cursor2, cursor_move2);
if(strcmp(cursor1->s,cursor2->s)!=0)
{
check=0;
break;
}
else
{
i++;
cursor_move2++;
}
}
}
if(check==0)
printf("%d Neg", check);
else
printf("1Pos");
}
void display(TOP *top)
{
STACK *cursor;
cursor=top->top;
while(cursor->next==NULL)
{
printf("%s pos\n ", cursor->s);
cursor=cursor->next;
}
}
int main()
{
char input[1000];
TOP top;
top.num=0;
top.top=NULL;
fgets(input, 100, stdin);
input[strlen(input)-1]='\0';
create_stack(&top, input);
printf("%d \n ", top.num);
display(&top);
printf("---------------------------------------------------------\n");
compare(&top);
return 0;
}
我建議你創建正確的'stack'功能(例如'pop'和'push'),這樣你就不需要一個'create_stack'函數將*整個*句子送入堆棧,因此您將擁有更多的靈活性。所以,然後你把你的字符串分成單詞(看看['strtok'](http://en.cppreference.com/w/c/string/byte/strtok)函數btw),把它們中的一半推到棧上,(在句子中增加字數時跳過一個單詞),然後在一個循環中:從棧中彈出一個,並與句子中的下一個比較 - 如果它們不匹配 - 終止它不是迴文。 –
你是否堅持解決這個問題的邏輯或實現? –
@AvantikaSaini我堅持實施。在上面的代碼中,由於某些原因(或者不打印)不會創建堆棧,這就是我卡住的地方。 –