第五周
栈的概念:
栈的基本运算:
栈分为顺序栈和链栈
- 像线性表一样,顺序存储结构称为顺序栈。
- 顺序栈由一个一维数组data和一个记录栈顶元素位置的变量top组成。
第六道 顺序栈
#include<iostream>
using namespace std;
#define max 100
typedef char ElemType;
typedef struct
{
ElemType data[max];
int top;
}List;
void Initstack(List& st)
{
st.top = -1;
}
int push(List& st, ElemType x)
{
if (st.top == max - 1) return 0;
else
{
st.top++;
st.data[st.top] = x;
return 1;
}
}
int pop(List& st, ElemType& x)
{
if (st.top == -1)
return 0;
else
{
x = st.data[st.top];
st.top--;
return 1;
}
}
int stackEmpty(List st)
{
if (st.top == -1)return 1;
else return 0;
}
void Destroylist(List st){}
int main()
{
List S;
int n;
char a[100],e,b[10];
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
Initstack(S);
if (stackEmpty(S))
cout << "yes" << endl;
else
cout << "no" << endl;
for (int i = 0; i < n; i++)
{
push(S, a[i]);
}
if (stackEmpty(S))
cout << "yes" << endl;
else
cout << "no" << endl;
cout << S.top + 1 << endl;
for (int i = 0; i < n; i++)//pop的话,栈空了
{
pop(S, b[i]);
}
for (int i = 0; i < n; i++)
cout << b[i]<<" ";
cout << endl;
for (int i = 0; i < n; i++)
cout << b[i]<<" ";
cout << endl;
if (stackEmpty(S))
cout << "yes" << endl;
else
cout << "no" << endl;
Destroylist(S);
return 0;
}
- 求长的算法没我想的那么难,写个函数之类的。s.top+1就可。
- 栈顶道栈底的顺序,没让把栈给pop出去
- 出栈的顺序
第九题 数制转换
#include<iostream>
using namespace std;
#define max 100
typedef int ElemType;
typedef struct
{
ElemType data[max];
int top;
}List;
void Initstack(List& st)
{
st.top = -1;
}
int push(List& st, ElemType x)
{
if (st.top == max - 1) return 0;
else
{
st.top++;
st.data[st.top] = x;
return 1;
}
}
int pop(List& st, ElemType& x)
{
if (st.top == -1)
return 0;
else
{
x = st.data[st.top];
st.top--;
return 1;
}
}
int stackEmpty(List st)
{
if (st.top == -1)return 1;
else return 0;
}
void Destroylist(List st) {}
int main()
{
List S;
Initstack(S);
int a,x;
int q,b[100];
cin >> a;
while (a> 0)//循环条件大于零即可
{
x = a% 8;
push(S, x);
a /= 8;
}
printf("转换成八进制为:");
while (!stackEmpty(S))
{
pop(S, x);
printf("%d", x);
}
cout << endl;
return 0;
}
如果不初始化,就会在push里报写入访问冲突的错。
第二道 括号匹配
呜呜呜,这个真的不会。今天还被助教挂在群里,社会性死亡了一次。
#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
stack<char> st;//可以直接调用
char t[1000];
int main()
{
cin >> t;
bool f = 1;//先这么预备着
for (int i = 0; i < strlen(t); i++) //扫描,计数,遇到\0停止
{
if (t[i] == '(' || t[i] == '[' || t[i] == '{')//左括号进栈
st.push(t[i]);
if (t[i] == ')' || t[i] == ']' || t[i] == '}')//遇到右括号,不进栈
{
if (st.empty())//如果已有的栈是空的,说明右括号是多余的
{
cout << "Extra right brackets" << endl;
f = 0;//
break;
}
else
{
int sum = (int)t[i] + (int)st.top();//强制转换成int,栈顶元素和数组内的元素相匹配
if (sum == 123 + 125 || sum == 91 + 93 || sum == 40 + 41)//左括号、右括号
{
st.pop();//符合的话,就出栈
continue;
}
else
{
cout << "Brackets not match" << endl;
f = 0;
break;
}
}
}
}
if (f)
{
if (st.empty())
cout << "Brackets match" << endl;
else
cout << "Extra left brackets" << endl;
}
return 0;
}
第六周啦,今天是周二,晚上又要去上数据结构。下午AC了3道OJ,大佬都过了一遍。还预习了队列。 差距啊。