3. 栈和队列的操作(8题)
<h1>1. 栈的构造和初始化</h1>
<pre><code class="language-c">#define maxSize 10
typedef struct{
int top;
char c[maxSize];
}stack;
stack* init(){
stack* s = (stack*)malloc(sizeof(stack));
s-&gt;top = -1;
return s;
}</code></pre>
<pre><code class="language-python">class stack_:
size = 10
def __init__(self):
self.top = -1
self.c = [None]*self.size</code></pre>
<h1>2. 入栈</h1>
<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>
<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>3. 出栈</h1>
<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>
<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>4. 获取栈顶元素</h1>
<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>
<pre><code class="language-python"> def getTop(self):
if(self.top == -1):
return 0
return self.c[self.top]</code></pre>
<h1>5. 循环队列构造与初始化</h1>
<pre><code class="language-c">#include&lt;stdio.h&gt;
#include&lt;stdlib.h&gt;
#define MaxSize 100
typedef struct{
int data[MaxSize];
int font;
int rear;
}queue;
queue* init(){
queue* q = (queue*)malloc(sizeof(queue));
q-&gt;font = 0;
q-&gt;rear = 0;
return q;
}</code></pre>
<pre><code class="language-python">class my_queue:
MaxSize = 100
def __init__(self):
self.data = [None]*self.MaxSize
self.front = 0
self.rear = 0</code></pre>
<h1>6. 循环队列入队</h1>
<pre><code class="language-c">int enQueue(queue* q, int t){
if(q-&gt;font==(q-&gt;rear+1)%MaxSize)
return 0;
q-&gt;rear = (q-&gt;rear+1)%MaxSize;
q-&gt;data[q-&gt;rear] = t;
return 1;
}</code></pre>
<pre><code class="language-python"> def enQueue(self, e):
if ((self.rear+1)%self.MaxSize == self.front):
return 0
self.rear = (self.rear+1)%self.MaxSize
self.data[self.rear] = e
return 1</code></pre>
<h1>7. 循环队列出队</h1>
<pre><code class="language-c">int deQueue(queue* q){
if(length(q) == 0)
return 0;
q-&gt;font = (q-&gt;font+1)%MaxSize;
int t = q-&gt;data[q-&gt;font];
return t;
}</code></pre>
<pre><code class="language-python"> def deQueue(self):
if (self.length() &gt; 0):
self.front = (self.front+1)%self.MaxSize
return self.data[self.front]
else:
return -1</code></pre>
<h1>8. 循环队列获取队列长度</h1>
<pre><code class="language-c">int length(queue* q){
return (q-&gt;rear+MaxSize - q-&gt;font) % MaxSize;
}</code></pre>
<pre><code class="language-python"> def length(self):
len = (self.rear+self.MaxSize-self.front) % self.MaxSize;
return len</code></pre>