2.2 栈的操作python(5段代码)
<h1>初始化一个栈</h1>
<pre><code class="language-python">class stack_:
size = 10
def __init__(self):
self.top = -1
self.c = [None]*self.size</code></pre>
<h1>入栈</h1>
<pre><code class="language-python"> def push(self, p):
if(self.top == self.size-1):
print(&quot;full&quot;)
return
self.top += 1
self.c[self.top] = p</code></pre>
<h1>出栈</h1>
<pre><code class="language-python"> def pop(self):
if(self.top == -1):
return 0
self.top -= 1
return self.c[self.top+1]</code></pre>
<h1>获取栈顶元素</h1>
<pre><code class="language-python"> def getTop(self):
if(self.top == -1):
return 0
return self.c[self.top]</code></pre>
<h1>格式化输出栈(不重要)</h1>
<pre><code class="language-python"> def show(self):
print(&quot;show stack:&quot;)
print(&quot;\t&quot;, end=&#039;&#039;)
for i in range(0, self.top+1):
print(&quot;\t{}&quot;.format(self.c[i]), end=&#039;&#039;)
print(&#039;\n\t&#039;, end=&#039;&#039;)
for i in range(0, self.top):
print(&quot;\t_&quot;, end=&#039;&#039;)
print(&quot;\t#&quot;, end=&#039;&#039;)
for i in range(self.top+1, self.size):
print(&quot;\t_&quot;, end=&#039;&#039;)
print()
for i in range(-1, self.size):
print(&quot;\t{}&quot;.format(i), end=&#039;&#039;)
print(&quot;\n\n&quot;)</code></pre>