Q:判斷一字符串是否爲迴文
A:對於這種要求輸入和輸出相反的情況,一般採用棧來解決,對於此題,只需將正序的字符串壓棧再將其全部彈出棧,判斷是否相同即可,代碼如下:
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 100
typedef int status;
typedef char elemtype;
typedef struct stack{
elemtype ch[MAXSIZE];
int top;
}stack;
status visit(elemtype c){
printf("%c ",c);
}
status initstack(stack *S){
S->top=-1;
}
status stacklength(stack *S){
return S->top+1;
}
status push(stack *S,elemtype data){
S->top++;
S->ch[S->top]=data;
}
status pop(stack *S,elemtype data){
data=S->ch[S->top];
S->top--;
}
status createstack(stack *S,elemtype start,elemtype end){
int i=0;
for(i=start;i<end;i++){
S->top++;
S->ch[S->top]=i;
}
}
status createstack2(stack *S,elemtype data){
S->top++;
S->ch[S->top]=data;
}
status traversestack(stack *S){
for(int i=S->top;i>=0;i--){
visit(S->ch[i]);
}
printf("\n");
}
status inversestack(stack *S,stack *S1){
for(int i=S->top;i>=0;i--){
if(S->ch[i]!=S1->ch[i])
return FALSE;
return TRUE;
}
}
int main(void){
stack S,S1;
initstack(&S);
initstack(&S1);
createstack(&S,'a','z');
for(char i='z';i>='a';i--){
push(&S,i);
}
traversestack(&S);
for(int i=S.top;i>=0;i--){
push(&S1,S.ch[i]);
}
traversestack(&S);
if(inversestack(&S,&S1))
printf("迴文\n");
else
printf("不是迴文\n");
}
Q:藉助棧,將單鏈表逆置
A:再次強調對於要求輸入輸出相反的題目,首先考慮用棧解決,將鏈表中所有元素壓棧,再彈出棧即可,代碼如下:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define ERROR 0
#define OK 1
#define TRUE 1
#define FALSE 0
#define maxsize 40
typedef int status;
typedef int elemtype;
//創建鏈表
struct node
{
elemtype data;
struct node *next;
}node;
typedef struct sqstack{
elemtype data[maxsize];
elemtype top;
}sqstack;
typedef struct node *linklist;
status visit(elemtype c)
{
printf("%d ",c);
return OK;
}
//初始化鏈表
status initlist(linklist *l)
{
(*l)=(linklist)malloc(sizeof(node));
if(!(*l))
return ERROR;
(*l)->next=NULL;
return OK;
}
//尾插法
status createlisttail(linklist *l,int n)
{
linklist p=*l,q;
int i;
srand(time(0));
for(i=0;i<n;i++)
{
q=(linklist)malloc(sizeof(node));
q->data=rand()%100;
p->next=q;
p=q;
}
p->next=NULL;
return OK;
}
status traverselist(linklist l)
{
linklist p=l->next;
while(p)
{
visit(p->data);
p=p->next;
}
printf("\n");
}
//將元素壓入棧
status push(sqstack *s,elemtype data)
{
if(s->top==maxsize-1){
return ERROR;//判斷棧是否已滿
}
else{
s->top++;
s->data[s->top]=data;
}
return OK;
}
//出棧並返回元素值
status pop(sqstack *s){
if(s->top==-1){
return ERROR;
}
else{
elemtype e;
e=s->data[s->top];
printf("%d ",e);
s->top--;
}
return OK;
}
status traversestack(sqstack *s){
int i=0;
for(i=s->top;i>=0;i--){
printf("%d ",s->data[i]);
}
printf("\n");
}
int main(void){
linklist l;
sqstack S;
initlist(&l);
int num;
scanf("%d",&num);
createlisttail(&l,num);
printf("整體創建l的元素(尾插法)\n");
traverselist(l);
linklist pmove=l->next;
while(pmove){
push(&S,pmove->data);
pmove=pmove->next;
}
for(int i=0;i<num;i++){
pop(&S);
}
}
Q;實現雙棧共享空間的出入棧算法
A:見拙作《雙棧共用存儲空間》,不再贅述