¾¡¹ÜBox ÀàÔÚ˵Ã÷Ò»¸öÀàµÄ±ØÒªµÄÔªËØʱÊÇÓÐÓõģ¬µ«Ëüʵ¼ÊÓ¦ÓõļÛÖµ²¢²»´ó¡£ÎªÁËÏÔʾ³öÀàµÄÕæʵµÄ¹¦ÄÜ£¬±¾Õ½«ÓÃÒ»¸ö¸ü¸´ÔÓµÄÀý×ÓÀ´ËµÃ÷ÀàµÄÇ¿´ó¹¦ÄÜ¡£Èç¹ûÄã»ØÒäÆðÔÚµÚ2ÕÂÖн²¹ýµÄÃæÏò¶ÔÏó±à³ÌµÄÌÖÂÛ£¬Äã¾Í»áÏëÆð¶ÔÏó±à³ÌµÄ×îÖØÒªµÄºÃ´¦Ö®Ò»ÊǶÔÊý¾ÝºÍ²Ù×÷¸ÃÊý¾ÝµÄ´úÂëµÄ·â×°¡£ÄãÒѾ֪µÀ£¬ÔÚJava ÖУ¬¾ÍÊÇͨ¹ýÀàÕâÑùµÄ»úÖÆÀ´Íê³É·â×°ÐÔ¡£ÔÚ´´½¨Ò»¸öÀàʱ£¬ÄãÕýÔÚ´´½¨Ò»ÖÖеÄÊý¾ÝÀàÐÍ£¬²»µ«Òª¶¨ÒåÊý¾ÝµÄÊôÐÔ£¬Ò²Òª¶¨Òå²Ù×÷Êý¾ÝµÄ´úÂë¡£½øÒ»²½£¬·½·¨¶¨ÒåÁ˶ԸÃÀàÊý¾ÝÏàÒ»ÖµĿØÖƽӿڡ£Òò´Ë£¬Äã¿ÉÒÔͨ¹ýÀàµÄ·½·¨À´Ê¹ÓÃÀ࣬¶øûÓбØÒªµ£ÐÄËüµÄʵÏÖϸ½Ú»òÔÚÀàµÄÄÚ²¿Êý¾Ýʵ¼ÊÉÏÊÇÈçºÎ±»¹ÜÀíµÄ¡£ÔÚijÖÖÒâÒåÉÏ£¬Ò»¸öÀàÏñ¡°Ò»Ì¨Êý¾ÝÒýÇ桱¡£Äã¿ÉÒÔͨ¹ý²Ù×ݸËÀ´¿ØÖÆʹÓÃÒýÇ棬¶ø²»ÐèÒªÖªµÀÒýÇæÄÚÊÇÈçºÎ¹¤×÷µÄ¡£ÊÂʵÉÏ£¬¼ÈȻϸ½Ú±»Òþ±Î£¬µ±ÐèҪʱ£¬ËüµÄÄÚ²¿¹¤×÷¿ÉÒÔ±»¸Ä±ä¡£Ö»ÒªÄãµÄ´úÂëͨ¹ýÀàµÄ·½·¨À´Ê¹ÓÃËü£¬ÄÚ²¿µÄϸ½Ú¿ÉÒԸıä¶ø²»»á¶ÔÀàµÄÍⲿ´øÀ´¸ºÃæÓ°Ïì¡£
ΪÁË¿´¿´Ç°ÃæÌÖÂÛ¸ÅÄîµÄÒ»¸öʵ¼ÊµÄÓ¦Óã¬ÈÃÎÒÃÇ¿ª·¢Ò»¸ö·â×°µÄµäÐÍÀý×Ó£º¶ÑÕ»£¨stack£©¡£¶ÑÕ»ÓÃÏȽøºó³öµÄ˳Ðò´æ´¢Êý¾Ý¡£¶Ñջͨ¹ýÁ½¸ö´«Í³µÄ²Ù×÷À´¿ØÖÆ£ºÑ¹Õ»£¨push£©ºÍ³öÕ»£¨pop£©¡£ÔÚ¶ÑÕ»µÄÉÏÃæ¼ÓÈëÒ»ÏÓÃѹջ£¬´Ó¶ÑÕ»ÖÐÈ¡³öÒ»ÏÓóöÕ»¡£Ä㽫¿´µ½£¬½«Õû¸ö¶ÑÕ»»úÖÆ·â×°ÊǺÜÈÝÒ׵ġ£
ÏÂÃæÊÇÒ»¸ö½Ð×öStackµÄÀ࣬ʵÏÖÕûÊýµÄ¶ÑÕ»¡£
// This class defines an integer stack that can hold 10 values.
class Stack {int stck[] = new int[10]; int tos;
// Initialize top-of-stack
Stack() {
tos = -1;
}
// Push an item onto the stack void push(int item) {if(tos==9) System.out.println("Stack is full."); else stck[++tos] = item; }
// Pop an item from the stack int pop() {
if(tos < 0) { System.out.println("Stack underflow."); return 0;
}
else
return stck[tos--];
}
}
ÕýÈçÄã¿´µ½µÄ£¬StackÀඨÒåÁËÁ½¸öÊý¾ÝÏî¡¢Èý¸ö·½·¨¡£ÕûÊý¶ÑÕ»ÓÉÊý×éstck´æ´¢¡£¸ÃÊý×éµÄϱêÓɱäÁ¿tos ¿ØÖÆ£¬¸Ã±äÁ¿×ÜÊÇ°üº¬¶ÑÕ»¶¥²ãµÄϱꡣStack()¹¹Ô캯Êý½«tos ³õʼ»¯Îª-1£¬ËüÖ¸ÏòÒ»¸ö¿Õ¶ÑÕ»¡£·½·¨push() ½«Ò»¸öÏîĿѹÈë¶ÑÕ»¡£ÎªÁËÖØÐÂÈ¡»ØѹÈë¶ÑÕ»µÄÏîÄ¿£¬µ÷ÓÃpop()¡£¼ÈÈ»´æÈ¡Êý¾Ýͨ¹ýpush()ºÍpop() £¬Êý×éÖд洢¶ÑÕ»µÄÊÂʵʵ¼ÊÉϺÍʹÓõĶÑÕ»²»Ïà¹Ø¡£ÀýÈ磬¶ÑÕ»¿ÉÒÔ±»´æ´¢ÔÚÒ»¸ö¸ü¸´ÔÓµÄÊý¾Ý½á¹¹ÖУ¬ÀýÈçÒ»¸öÁ´±í£¬µ«push()ºÍpop() ¶¨ÒåµÄ½Ó¿ÚÈÔÈ»ÊÇÒ»ÑùµÄ¡£
ÏÂÃæʾÀýµÄÀàTestStack£¬ÑéÖ¤ÁËStackÀà¡£¸ÃÀà²úÉúÁ½¸öÕûÊý¶ÑÕ»£¬½«Ò»Ð©Öµ´æÈ룬Ȼºó½«ËüÃÇÈ¡³ö¡£
class TestStack {
public static void main(String args[]) {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
// push some numbers onto the stack
for(int i=0; i<10; i++) mystack1.push(i);
for(int i=10; i<20; i++) mystack2.push(i);
// pop those numbers off the stack
System.out.println("Stack in mystack1:");
for(int i=0; i<10; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<10; i++)
System.out.println(mystack2.pop());
}
}
¸Ã³ÌÐò²úÉúµÄÊä³öÈçÏ£º
Stack in mystack1:
9
8
7
6
5
4
3
2
1
0
Stack in mystack2:
19
18
17
16
15
14
13
12
11
10
ÄãÒѾ¿´µ½£¬Ã¿¸ö¶ÑÕ»ÖеÄÄÚÈÝÊÇ·ÖÀëµÄ¡£
¹ØÓÚStack ÀàµÄ×îºóÒ»µã¡£ÕýÈçËüÏÖÔÚÖ´ÐеÄÒ»Ñù£¬Í¨¹ýStack ÀàÍâÃæµÄ´úÂë¿ÉÒԸı䱣´æ¶ÑÕ»µÄÊý×éstck ¡£ÕâÑùµÄStack ÊÇ¿ª·ÅµÄ£¬ÈÝÒ×ÎóÓûòË𻵡£ÔÚÏÂÒ»ÕÂÖУ¬Ä㽫»á¿´µ½ÈçºÎ²¹¾ÈÕâÖÖÇé¿ö¡£