在程序設計中,大家一定接觸過“堆棧”,其實堆和棧是兩個完全不同的概念,棧是一種特殊的數據結構。在中斷處理中常用來保護現場。
在棧的結構中,只能在棧的一端進行數據操作,這一端成爲棧頂,另一端成爲棧底。即:數據的存取只能在棧頂進行。從數據運算的角度來分析,棧結構式按照“後進先出”(Last In Firt OUT,LIFO)的原則處理結點的。
1.數據準備部分
<h3><pre name="code" class="java"><span style="font-weight: normal;"><span style="font-size:14px;">//數據</span></span>
<span style="font-weight: normal;"><span style="font-size:14px;">class DATA
{
String name;
int age;
}
//結構
class StackType
{
static final int MAXLEN=50;
DATA3[] data=new DATA3[MAXLEN+1]; //數據元素
int top; //棧頂 </span></span>
<span style="font-family: Arial, Helvetica, sans-serif; font-weight: normal;"><span style="font-size:10px;"> }</span></span>
2.初始化棧
<span style="font-weight: normal;"> StackType STInit()
{
StackType p;
if((p=new StackType())!=null) //申請棧內存
{
p.top=0; //設置棧頂爲0
return p; //返回指向棧的指針
}
return null;
}</span>
3.判斷棧空/棧滿
<span style="font-weight: normal;"> boolean STIsEmpty(StackType s) //判斷棧是否爲空
{
boolean t;
t=(s.top==0);
return t;
}</span>
<span style="font-weight: normal;"> boolean STIsFull(StackType s) //判斷棧是否已滿
{
boolean t;
t=(s.top==MAXLEN);
return t;
}</span>
4.清空棧/釋放空間
<span style="font-weight: normal;"> void STClear(StackType s) //清空棧
{
s.top=0;
}</span>
<span style="font-weight: normal;"> void STFree(StackType s) //釋放棧所佔用空間
{
if(s!=null)
{
s=null;
}
}</span>
5.入棧/出棧
<span style="font-weight: normal;"> int PushST(StackType s,DATA3 data) //入棧操作
{
if((s.top+1)>MAXLEN)
{
System.out.print("棧溢出!\n");
return 0;
}
s.data[++s.top]=data; //將元素入棧
return 1;
}
</span>
<span style="font-weight: normal;">
DATA PopST(StackType s) //出棧操作
{
if(s.top==0)
{
System.out.print("棧爲空!\n");
//
System.exit(0);
}
return (s.data[s.top--]);
}
</span>
6.讀取結點數據
<span style="font-weight: normal;"> DATA PeekST(StackType s) //讀棧頂數據
{
if(s.top==0)
{
System.out.printf("棧爲空!\n");
//
System.exit(0);
}
return (s.data[s.top]);
}
}</span>
以上就是數據結構中的棧。