正文
小伙伴们,你们好呀!我是老寇!
栈是一种特殊的线性表,并且只能一端进行插入和删除操作
本文采用链表来创建栈
1.创建一个节点的类
package cn.itcast.com.istack; public class Node { public Object data; public Node next; public Node(Object data) { this(data,null); } public Node() { this(null,null); } public Node(Object data,Node next) { this.data=data; this.next=next; } }
2.创建接口
package cn.itcast.com.istack; public interface IStack { public void clear();//将栈置空 public boolean isEmpty();//判断为空 public void push(Object x);//压入栈 public Object pop();//移出栈顶 public Object peek();//查看栈顶 public void display();//打印 public int length();//长度 }
3.实现接口
package cn.itcast.com.istack; /*** * 尾插法 * **/ public class LinkStack implements IStack{ public Node top; @Override public void clear() { top=null; } @Override public boolean isEmpty() { return top==null; } @Override public void push(Object x) { Node p=new Node(x); p.next=top; top=p; } @Override public Object pop() { if(!isEmpty()) { Node p=top; top=top.next; return p.data; }else { return null; } } @Override public Object peek() { if(!isEmpty()) { return top.data; }else { return null; } } @Override public void display() { Node p=top; while(p!=null) { System.out.print(p.data.toString()+" "); p=p.next; } System.out.println(); } @Override public int length() { Node p=top; int length=0; while(p!=null) { length++; p=p.next; } return length; } public static void main(String[] args) { System.out.println("栈中各元素为(栈顶到栈底):"); LinkStack S=new LinkStack(); for(int i=1;i<=10;i++) { S.push(i); } S.display(); if(!S.isEmpty()) { System.out.println("栈非空!"); } System.out.println("栈的长度为:" +S.length()); System.out.println("栈顶元素为:"+S.peek()); System.out.println("去除栈顶元素后,栈中各元素为(栈顶到栈底):"); S.pop(); S.display(); System.out.println("去除栈中剩余的所有元素! 进行中。。。"); S.clear(); if(S.isEmpty()) { System.out.println("栈为空!"); } } }
4.运行结果