小猫钓鱼–栈和队列的使用
思路
q1和q2手中的牌分别是一个队列,桌面上的牌是一个栈,用book数组标记桌面上出现的牌。
代码
#include <stdio.h>
struct queue
{
int data[1000];
int head;
int tail;
};
struct stack
{
int data[10];
int top;
};
int main()
{
int a[6] = {2, 4, 1, 2, 5, 6};
int b[6] = {3, 1, 3, 5, 6, 4};
int book[10];
struct queue q1, q2;
struct stack s;
int i, t, flag;
q1.head = 0; q1.tail = 0;
q2.head = 0; q2.tail = 0;
s.top = -1;
for (i = 0; i< 10; i++) {
book[i] = 0;
}
for (i = 0; i < 6; ++i) {
q1.data[q1.tail] = a[i];
q1.tail++;
q2.data[q2.tail] = b[i];
q2.tail++;
}
while (q1.head < q1.tail && q2.head < q2.tail) {
t = q1.data[q1.head];
printf("q1: %d\n", t);
if (book[t] == 0) {
q1.head++;
s.top++;
s.data[s.top] = t;
book[t] = 1;
} else {
q1.head++;
q1.data[q1.tail] = t;
q1.tail++;
while(s.data[s.top] != t) {
book[s.data[s.top]] = 0;
q1.data[q1.tail] = s.data[s.top];
q1.tail++;
s.top--;
}
}
t = q2.data[q2.head];
printf("q2: %d\n", t);
if (book[t] == 0) {
q2.head++;
s.top++;
s.data[s.top] = t;
book[t] = 1;
} else {
q2.head++;
q2.data[q2.tail] = t;
q2.tail++;
while(s.data[s.top] != t) {
book[s.data[s.top]] = 0;
q2.data[q2.tail] = s.data[s.top];
q2.tail++;
s.top--;
}
}
}
if (q1.head == q1.tail) {
printf("q2 \n");
for (i = q2.head; i < q2.tail; ++i) {
printf("%d ", q2.data[i]);
}
}
if (q2.head == q2.tail) {
printf("q1 \n");
for (i = q1.head; i < q1.tail; ++i) {
printf("%d ", q1.data[i]);
}
}
if (s.top > 0) {
printf("\n桌面上的牌是 ");
for (i = 0; i <= s.top; ++i) {
printf("%d ", s.data[i]);
}
} else {
printf("\n桌上已经没有牌了");
}
return 0;
}
结果:
5 6 2 3 1 4 6 5
桌面上的牌是 2 1 3 4
python 代码:
q1 = [2, 4, 1, 2, 5, 6]
q2 = [3, 1, 3, 5, 6, 4]
book = {}
s = []
while len(q1) !=0 and len(q2) != 0 :
t = q1.pop(0)
print("q1: %d" % t)
if t not in book.keys() or book[t] == 0:
s.append(t)
book[t] = 1
else:
q1.append(t)
while s[-1] != t:
top = s[-1]
q1.append(top)
s.pop()
book[top] = 0
t = q2.pop(0)
print("q2: %d" % t)
if t not in book.keys() or book[t] == 0:
s.append(t)
book[t] = 1
else:
q2.append(t)
while s[-1] != t:
top = s[-1]
q2.append(top)
s.pop()
book[top] = 0
if len(q1) == 0:
print("q2 win")
print(q2)
else:
print("q1 win")
print(q1)
if len(s) != 0:
print("table")
print(s)
else:
print("not table")