如何实现在Java界栈10金钱.anslist{background:url(source/plugin/keke_ans
技术问答
300 人阅读
|
0 人回复
|
2023-09-11
|
我需要帮助的事情是:; W3 |0 V% z. d. f, }
3 v" k! [& k; }! r. ~6 o9 o
- 什么是正确的代码,以使的isEmpty()和isFull()方法返回一个答案,告诉我,如果堆栈是空的,或者如果堆栈已满" X2 z* ^; \( |; O/ U/ ~) n
- 我需要让我的筹码我使用的是五(5)的一组大小(堆栈可容纳5个整数)我需要在添加例外推()和pop()方法,即不让推时使用堆栈已满,或当栈为空弹出使用
3 S8 L" i" s( Q9 u' J$ v' X0 r # f3 ]' O u- w8 K- u
- import java.util.ArrayList;
+ c+ ?0 N2 V3 x! K8 v - import java.util.List;
, {& S5 U5 h6 w. B6 M6 z3 K/ a - - @* P2 a% r2 K" V
- public class IntegerStack {$ [' g3 W3 m G$ y3 T
J% T9 F2 [6 e: k) _' _- private List<Integer> stack;5 o$ D3 E ~! O9 i2 |. [
- 3 r! K+ e6 {# f# ~0 a: M; Y8 l% Z& n/ U
- public IntegerStack(int SIZE) {6 {8 ~; Z2 n8 j% b8 E% g
- stack = new ArrayList<Integer>(SIZE);; s9 u1 g5 I( D G- I
- }
, n' a1 q5 P; n2 ?1 r0 B# F - * ^. N' C, O! c# d: y: Y
- /* method to push the stack */6 a5 h+ S# `) m% y4 b: B6 h7 ^; }
- public void push(int i) {' }, w7 s9 u' [3 X7 K6 I
- 6 N7 K4 l1 E3 U5 ?5 I$ J1 f
- stack.add(0, i);; W" J, s% ?( F/ V2 M% W/ i/ ?
- }
2 ]% P7 S& F7 F9 @
/ @6 O- ?0 ^5 I3 Z6 }" \- /* method to pop the stack */9 {! J, @- O) ?5 s1 p! Q: I
- public int pop() {7 k' d( o P9 ~0 x) Q. X- d8 f$ g" o
- if (!stack.isEmpty()) {- e0 \2 X- ?# ?9 u `& O
- int i = stack.get(0);
6 S; ~3 n1 y3 Q9 z% I i0 e - stack.remove(0);
! U, k+ q& u% _2 K+ x4 M - return i;& L+ T) C$ U+ r4 i9 D
- } else {) P5 T" P, u) \ d/ F
- return -1;// Or any invalid value
; C) y0 }+ h3 G9 `3 i* }# i: \ - }
5 O3 {/ z% Q, H3 y @$ F/ G2 | - }' P& M0 T8 r/ r n9 i5 G$ I
- 2 L" V W# Y6 M# n+ {
- /* method to peek at the stack */
: y/ `0 }2 \5 {' {7 R: Z+ X - public int peek() {
% Q# [( b( K* M6 h - if (!stack.isEmpty()) {: c. H$ B! O( j7 I$ e" G5 ^
- return stack.get(0);3 I# G4 \8 }: Y' W$ m% `
- } else {
9 T8 K* v) Q9 U9 u4 [0 E - return -1;// Or any invalid value
: z$ l, y, _* n5 j. G1 K5 l - }
4 E" p. @6 `4 {. f$ ] - }; @" J, T' B. Y+ J2 @4 s5 g/ I. E& T
- $ G- t/ I+ E$ }
- /* determine if the stack is empty */2 Z6 P0 j% ]- B6 M' n; F. m
- public boolean isEmpty() {
5 h9 _/ H+ s' o# y% } - stack.isEmpty();& ]' m3 {, R8 Z: p: [7 p* k
- }" @' G7 M6 g/ a
6 {9 E1 ~4 h- Y4 \) e- /* determine if the stack is full */* W) E* R. q% x, ]
- public boolean isFull() {
. x3 |% O; u* l* U# c - stack.isFull(); N" k# X, D, C. S
- }, ^- j# I& N! f9 f; {. H
- 1 z9 w* P0 r$ _' I, ~
- /* determine the size of the stack */! n/ Y4 |. G( J' ~+ C- b1 A, M
- public int size() {
. ?. o% S v* J: Y - if (stack.isEmpty())
+ }( `; ~0 u" k' j- g1 e - return 0;+ d* ~/ b! p0 u7 D: N( V: R
- else
9 I7 D( I. H) j8 w" c2 ?* S; `9 M - return stack.size();
* P: W1 r; e7 w; G% J2 @ - }; e* k% X* w- i) c
- }
& t: `& r3 Q5 c3 Y, \ " P g0 Y1 t( d7 N& H
2 ?* N$ U: g& V D: K
我知道答案 回答被采纳将会获得10 金钱 已有0人回答 |
|
|
|
|
|