棧的練習
聲明,練習是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");
}