利用栈判断镜像串

建议使用vs for 2019

#include<stdio.h>
#include<stdlib.h>
#include<string.h> 

typedef struct StackNode {
    
    
	char data;//数据域 
	struct StackNode* next;//指针域 
}StackNode, * StackLink;//用于指向该类型结构体 

typedef struct StackNodePre node;

struct StackNodePre {
    
    
	StackLink top;// 栈顶指针 
	int amount;//计算栈内元素的数量 
};
//传入栈顶指针和压入值
node* Push(node* S, char PushAmount)//入栈 
{
    
    
	if (S->amount == 0) {
    
    //栈为空 
		StackNode* p = (StackNode*)malloc(sizeof(StackNode));
		if (p) {
    
    
			S->top = p;//指向p空间
			p->next = NULL;//空
			p->data = PushAmount;//赋值
			++S->amount;//栈内元素加一
		}

		return S;
	}
	else {
    
    
		StackNode* p = (StackNode*)malloc(sizeof(StackNode));
		if (p) {
    
    //上同
			p->next = S->top;
			p->data = PushAmount;
			S->top = p;
			++S->amount;
		}

		return S;
	}

}

node* Pop(node* S)//出栈
{
    
    
	if (S->amount == 0) {
    
    
		return S;
	}
	else {
    
    
		StackLink p;
		p = S->top;//保存
		S->top = S->top->next;//移动栈顶指针 
		free(p);//释放空间
		--S->amount;
		return S;
	}

}

int main()
{
    
    	
	int i, j, Length = 0;
	char a[] = "AEHIJLMOSTUVWXYZ12358";//记录下所有镜像串
	char b[] = "A3HILJMO2TUVWXYZ1SEZ8";
	node* S = (node*)malloc(sizeof(node));
	if (S) {
    
    
       S->top = NULL;//初始化
	   S->amount = 0;//初始化
	   /*建栈*/
	   char str[101];
	   scanf_s("%s", str, 100);
	   str[100] = '\0';
	   while (Length < strlen(str)) {
    
    
		   S = Push(S, str[Length]);
		   ++Length;
	   }
	   
	   /*查找并判断*/
	   StackLink p = S->top;
	   if (p) {
    
    
		   int h = 0;
		   for (i = 0, j = 0; i < strlen(a) && j < Length / 2; i++) {
    
    
			   if (p->data == a[i]) {
    
    
				   while (h < Length - 1 - j) {
    
    //使P指向对应的结点
					   p = p->next;
					   ++h;
				   }
				   if (p->data != b[i])break;
				   else {
    
    
					   S = Pop(S);
					   ++j;
					   i = 0;//刷新
				   }
				   p = S->top;//刷新
				   h = j;//刷新
			   }
		   }
		   if (j != Length / 2)
			   printf("%s--is not a mirrored string", str);
		   else
			   printf("%s--is a mirrored string", str);
	   }
	   
	}
	
	
}

猜你喜欢

转载自blog.csdn.net/qq_52001969/article/details/113571586