class="MsoNormal" style="text-align: center;">Java数据结构(二)
——栈
栈是一种特殊的线性表。栈的数据元素以及数据元素的逻辑关系和线性表完全相同,其差别是线性表允许在任意位置进行插入和caozuo.html" target="_blank">删除操作,而栈只允许在固定一段进行插入和删除操作。栈中允许进行插入和删除操作的一段称为栈顶,另一端称为栈底。栈的插入操作通常我们都成为进栈或入栈~~而删除操作通常称为出栈或退栈。
根据栈的定义,每次进栈的数据元素都放在原当前栈顶元素之前而成为新的栈顶元素,每次退栈的数据元素都是当前栈顶元素,这样,最后进入栈的数据元素总是最先退出栈,因此栈也被称为后进后出表。
顺序栈
?
Java代码?
- package?pzw.Stack;??
- ?
- ?
- ?
- ?
- ??
- public?class?SeqStack?implements?Stack{??
- ??????
- ????final?int?defaultSize?=?10;??
- ????int?top;??
- ????Object[]?stack;??
- ????int?maxStackSize;??
- ??????
- ????public?SeqStack(){??
- ????????initiate(defaultSize);??
- ????}??
- ??????
- ????public?SeqStack(int?size){??
- ????????initiate(size);??
- ????}??
- ??????
- ????private?void?initiate(int?sz){??
- ????????maxStackSize?=?sz;??
- ????????top?=?0;??
- ????????stack?=?new?Object[sz];??
- ????}??
- ??????
- ????public?void?push(Object?elm)?throws?Exception?{??
- ????????if(top?==?maxStackSize){??
- ????????????throw?new?Exception("该堆栈已满");??
- ????????}??
- ????????stack[top]?=?elm;??
- ????????top++;??
- ????}??
- ??
- ????public?Object?pop()?throws?Exception?{??
- ????????if(top?==?0){??
- ????????????throw?new?Exception("该堆栈已空");??
- ????????}??
- ????????top--;????
- ????????return?stack[top];??
- ????}??
- ??
- ????public?Object?getTop()?throws?Exception?{??
- ????????if(top?==?0){??
- ????????????throw?new?Exception("该堆栈已空");??
- ????????}??
- ????????return?stack[top-1];??
- ????}??
- ??
- ????public?boolean?notEmpty()?{??
- ??????????
- ????????return?top?>?0;??
- ????}??
- ??
- }??
?
链式栈
?
Java代码?
- package?pzw.Stack;??
- ?
- ?
- ?
- ?
- ??
- public?class?LinStack?implements?Stack{??
- ????public?Node?top;??
- ????public?int?size;??
- ??????
- ??????
- ????public?LinStack(){??
- ????????top?=?null;??
- ????????size?=?0;??
- ????}??
- ??????
- ????public?void?push(Object?elm)?throws?Exception?{??
- ????????top?=?new?Node(elm,top);??
- ????????size++;??
- ????}??
- ??
- ????public?Object?pop()?throws?Exception?{??
- ????????if(size?==?0){??
- ????????????throw?new?Exception("该堆栈已空");??
- ????????}??
- ????????Object?elm?=?top.elm;??
- ????????top?=?top.next;??
- ????????size--;??
- ????????return?elm;??
- ????}??
- ??
- ????public?Object?getTop()?throws?Exception?{??
- ????????if(size?==?0){??
- ????????????throw?new?Exception("该堆栈已空");??
- ????????}??
- ??????????
- ????????return?top.elm;??
- ????}??
- ??
- ????@Override??
- ????public?boolean?notEmpty()?{??
- ??????????
- ????????return?size?>?0;??
- ????}??
- ??
- } ?
- Stack.zip (2.4 KB)
- 描述: 栈的实现
- 下载次数: 0