栈和队列练习

栈的练习

声明,练习是2020春XDU我的数据结构作业 程序保证做到可以跑 主要给我自己复习 可以参考 但不要完整抄去交作业 3Q 非常欢迎私信交流更简单的做法

T11配对

设单链表中存放n个字符,编写算法判断该字符串是否有中心对称关系
(提示:将一半字符先依次进栈)

#include<stdio.h>//symmetry 对称 配对 
#include<stdlib.h>
#include<stack>
using namespace std;
stack <char> st;
typedef struct node *List;
struct node
{
	char data;
	List next;
};
List creat()
{
	int k;
	List s,head;
	List L=(List)malloc(sizeof(struct node));
	L->next=NULL;
	head=L; 
	printf("please enter list until #\n");
	while(1)
	{
		scanf("%c",&k);
		if(k=='#') break;
		else
		{
			s=(List)malloc(sizeof(struct node));
			s->data=k;
			s->next=L->next;
			L->next=s;
		}
	}
	return head;
}

bool symmetry(List L,int n)
{
	List p=L->next;
	int total=n;
	int cnt=1;//计数器 
	while(p!=NULL&&cnt<=total/2)
	{
		st.push(p->data);
		p=p->next;
		cnt++;
	}
	if(total%2==1) p=p->next;
	while(!st.empty())
		{
			if(st.top()!=p->data) return false;
			else p=p->next;
			st.pop();
		}
	if(st.empty()) return true;
 }
 
int main()
{
	int n;
	printf("n=");
	scanf("%d",&n);
	List L=creat();
	if(symmetry(L,n)) printf("yes\n");
	else printf("no\n");
} 

T12 括号匹配

经典的题目
凡遇到( 进栈,遇到 ‘)’退栈 表达式扫描完毕,栈应为空

#include<stdio.h>
#include<stdlib.h>
#include<string.h> 
#include<stack>
using namespace std;
stack <char> s;
int main()
{
	char a[100];
	printf("please enter string\n");
	scanf("%s",a);
	int i;
	for(i=0;i<strlen(a);i++)
	{
		if(a[i]=='(') s.push(a[i]);
		else if(a[i]==')')
		{
			s.pop();
		}
	}
	if(s.empty()) printf("yes");
	else printf("no");
}

括号匹配2

三种括号{}的匹配

#include<stdio.h>
#include<stdlib.h>
#include<string.h> 
#include<stack>
using namespace std;
stack <char> s;
int main()
{
	char a[100],tmp;
	printf("please enter string\n");
	scanf("%s",a);
	int i;
	for(i=0;i<strlen(a);i++)
	{
		if(a[i]=='('||a[i]=='['||a[i]=='{') s.push(a[i]);
		else if(a[i]==')')
		{
			if(s.top()=='(') s.pop();
			else break;
		}
		
		else if(a[i]==']')
		{
			if(s.top()=='[') s.pop();
			else break;
		}
		
		else if(a[i]=='}')
		{
			if(s.top()=='{') s.pop();
			else break;
		}
	}
	if(s.empty()) printf("yes");
	else printf("no");
}
发布了46 篇原创文章 · 获赞 13 · 访问量 3679

猜你喜欢

转载自blog.csdn.net/qq_39679772/article/details/104726057
今日推荐