2.1 栈的操作C(6段代码)
<h2>栈的结构体</h2>
<pre><code class="language-c">#define maxSize 10
typedef struct{
int top;
char c[maxSize];
}stack;</code></pre>
<h2>栈的初始化</h2>
<pre><code class="language-c">stack* init(){
stack* s = (stack*)malloc(sizeof(stack));
s-&gt;top = -1;
return s;
}</code></pre>
<h2>入栈</h2>
<pre><code class="language-c">void push(stack* s, char p){
if(s-&gt;top == maxSize-1){
printf(&quot;full&quot;);
return;
}
s-&gt;top += 1;
s-&gt;c[s-&gt;top] = p;
}</code></pre>
<h2>出栈</h2>
<pre><code class="language-c">char pop(stack* s){
if(s-&gt;top == -1){
return 0;
}
return s-&gt;c[s-&gt;top--];
}</code></pre>
<h2>获取栈顶元素</h2>
<pre><code class="language-c">char getTop(stack* s){
if(s-&gt;top == -1){
return 0;
}
return s-&gt;c[s-&gt;top];
}</code></pre>
<h2>格式化输出栈(不重要)</h2>
<pre><code class="language-c">void show(stack* s){
int i;
printf(&quot;show stack:\n&quot;);
printf(&quot;\t&quot;);
for(i=0; i&lt;=s-&gt;top; i++){
printf(&quot;\t%c&quot;, s-&gt;c[i]);
}
printf(&quot;\n&quot;);
for(i=-1; i&lt;s-&gt;top; i++){
printf(&quot;\t_&quot;);
}
printf(&quot;\t#&quot;);
for(i=s-&gt;top+1; i&lt;maxSize; i++){
printf(&quot;\t_&quot;);
}
printf(&quot;\n&quot;);
for(i=-1; i&lt;maxSize; i++){
printf(&quot;\t%d&quot;, i);
}
printf(&quot;\n\n\n&quot;);
}
</code></pre>