那么,栈其实是链表的特殊形式,我们引进了一种叫做top的指针来表示栈的栈顶,栈顶指针top实际只能指向栈的最后一个数据,并且遵循先进后出的规则,由栈顶指针统筹,永远指向栈顶。
- 添加数据(入栈)只能在栈顶加入
- 删除数据(出栈)只能从栈顶删除
- 其他数据即栈头,栈内的数据不允许直接入栈和出栈
链栈:
public class linkStrack{
private Node top;
private int length;
public linkStrack() {
top = null ;
length = 0;
}
// 添加数据,从尾部添加数据
public void push(int date) {
Node pNode = new Node(date);
if (top==null) {
top=pNode;
}else {
pNode.next=top;
/* pnode --> 7
* top(pnode.next) --> 6
* ...
* 第二步:
* top --> 7
* ...
*
*/
top=pNode;
}
length++;
}
public int pop() {
if (top == null) {
System.out.println("栈空,无法删除元素");
}
int x = top.date;
// top的下一位传入top
top=top.next;
length--;
return x;
}
public void getHead() {
if (top == null) {
System.out.println("栈空,无法获取元素");
}
System.out.println("head:"+top.date);
}
public int size() {
return length;
}
public boolean isEmpty() {
return top == null;
}
public void print() {
Node p = top;
while(p!= null) {
System.out.print(p.date+" ");
p=p.next;
}
System.out.println("");
}
public void clear() {
top = null;
}
public static void main(String[] args) {
linkStrack is = new linkStrack();
int[] a = {1,2,3,4,5,6,7};
for (int i = 0; i < a.length; i++) {
is.push(a[i]);
}
is.print();
is.pop();
is.print();
is.getHead();
System.out.println("元素个数:"+is.size());
}
}
顺序栈:
public class sequenceStrack<T>{
public static int top;
public static int size;
public static int maxSize = 10;//10个元素
public static Object[] StrackArray ;
public sequenceStrack() {
top = -1;
StrackArray = new Object[maxSize];
}
public sequenceStrack(int n) {
if(n<=0) {
System.out.println("无效");
System.exit(1);
}
top = -1;
StrackArray = new Object[maxSize];
}
public void push(Object date) {
//栈空间的扩建
//full();
StrackArray[++top] = (int)date;
}
public void full() {
if(top ==maxSize){
Object []p = new Object[top*2+2];
for(int i =0;i<=top;i++) {
p[i] = StrackArray[i];
StrackArray = p;
}
}
}
public void pop() {
check(top);
top--;
//往前移一步,也可以不用写
StrackArray[top+1] = StrackArray[top];
}
public int getHead(){
check(top);
System.out.println(StrackArray[top]);
return (int) StrackArray[top];
}
public Object check(int top) {
if(top==-1) {
System.out.println("数据栈已空,无法进行程序");
return null;
}
return top;
}
public int isEmpty() {
return top = -1;
}
public int size() {
return top+1;
}
public void print() {
for(int i= top;i>=0;i--) {
System.out.print(StrackArray[i]+" ");
}
System.out.println("");
}
public void clear() {
top = -1;
}
public static void main(String[] args) {
sequenceStrack link = new sequenceStrack();
int[] a = {1,2,3,4,5,6,7,9,4,3};
for (int i = 0;i < a.length; i++) {
link.push(a[i]);
}
link.print();
link.pop();
link.print();
link.getHead();
}
}