題目要求:
兩人比賽,a,b,每人最開始分得6張手牌,手牌大小為從1到9
a先出牌,b后出牌,若出牌在桌面上存在,在出牌人獲得兩張相同牌中間的所有牌(包括兩張相同牌),放入出牌人手中。
最后誰手中無牌判為負
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
import java.util.linkedlist; import java.util.queue; import java.util.scanner; import java.util.stack; /** * 模擬實現兩人玩小貓釣魚游戲 * 判斷誰先出完誰獲勝 * @author zyk * */ public class playgame { public static void main(string[] args) { stack<integer> deskstack = new stack<>(); //桌子上的牌,用棧進行管理 queue<integer> playera = new linkedlist(); //用隊列管理每個選手的牌 queue<integer> playerb = new linkedlist(); int book[] = new int [ 10 ]; scanner scanner = new scanner(system.in); //發牌,每人6張 for ( int i = 0 ; i < 6 ; i++) { playera.add(scanner.nextint()); } for ( int i = 0 ; i < 6 ; i++) { playerb.add(scanner.nextint()); } //當兩個隊列都不為空,表示游戲沒有結束 while (!playera.isempty() && !playerb.isempty()) { int ta = playera.peek(); //a出一張牌 //判斷a出的牌能不能贏牌 if (book[ta] == 0 ) { //桌子上沒有這張牌 //a不能贏牌 playera.remove(); //打出的牌出隊列 deskstack.add(ta); //打出的牌入棧 book[ta]= 1 ; //標記打出的牌出現在桌子上 } else { //a能贏牌 playera.remove(); //打出的牌出隊列 playera.add(ta); //打出的牌入隊列 while (deskstack.lastelement()!=ta) { book[deskstack.lastelement()] = 0 ; playera.add(deskstack.lastelement()); deskstack.pop(); } } int tb = playerb.peek(); //b出一張牌 //判斷b出的牌能不能贏牌 if (book[tb] == 0 ) { //桌子上沒有這張牌 //b不能贏牌 playerb.remove(); //打出的牌出隊列 deskstack.add(tb); //打出的牌入棧 book[tb]= 1 ; //標記打出的牌出現在桌子上 } else { //b能贏牌 playerb.remove(); //打出的牌出隊列 playerb.add(tb); //打出的牌入隊列 while (deskstack.lastelement()!=tb) { book[deskstack.lastelement()] = 0 ; playerb.add(deskstack.lastelement()); deskstack.pop(); } } } if (playera.isempty()) { system.out.println( "b贏了" ); system.out.print( "b手中的牌為:" ); while (!playerb.isempty()) { system.out.print(playerb.peek()+ " " ); playerb.remove(); } } else { system.out.println( "a贏了" ); system.out.print( "a手中的牌為:" ); while (!playera.isempty()) { system.out.print(playera.peek()+ " " ); playera.remove(); } } system.out.println( "" ); system.out.print( "桌子上的牌為:" ); while (!deskstack.isempty()) { system.out.print(deskstack.lastelement()+ " " ); deskstack.pop(); } } } |
實例:
輸入:
2 4 1 2 5 6
3 1 3 5 6 4輸出:
a贏了
a手中的牌為:5 6 2 3 1 4 6 5
參考: 《啊哈算法》第二章 棧,隊列,鏈表
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/u011896903/article/details/52015166