栈与链栈 一,顺序栈 1.1 IStack栈接口 1.2,顺序栈增删改查的实现 1.3,测试顺序栈 二,链栈 2.1,存放数据的结点 2.2,链栈的实现 2.3测试链栈
一,顺序栈
1.1 IStack栈接口
public interface IStack { public void clear ( ) ; public boolean isEmpty ( ) ; public int length ( ) ; public Object peek ( ) ; public void push ( Object x) ; public Object pop ( ) ; public void display ( ) ;
}
1.2,顺序栈增删改查的实现
public class SeqStack implements IStack { private Object[ ] stackElem; private int top; private int maxSize; public SeqStack ( int maxSize) { top = 0 ; this . maxSize = maxSize; stackElem = new Object [ maxSize] ; } public void clear ( ) { top = 0 ; } public boolean isEmpty ( ) { return top == 0 ; } public int length ( ) { return top; } public Object peek ( ) { if ( ! isEmpty ( ) ) return stackElem[ top - 1 ] ; return null; } public void push ( Object x) { if ( top == maxSize) { System. out. println ( "栈已满" ) ; return ; } stackElem[ top] = x; top ++ ; } @Override public Object pop ( ) { if ( ! isEmpty ( ) ) { top -- ; return stackElem[ top] ; } return null; } public void display ( ) { for ( int i = top - 1 ; i >= 0 ; i-- ) { System. out. print ( stackElem[ i] + " " ) ; } System. out. println ( ) ; } }
1.3,测试顺序栈
public class TestSeqStack { public static void main( String[ ] args) { SeqStack seqStack = new SeqStack( 3 ) ; seqStack. push( "abc" ) ; seqStack. push( "def" ) ; seqStack. push( "ghi" ) ; // 返回栈顶元素Object peekEle = seqStack. peek( ) ; System. out. println( "栈顶元素" + peekEle) ; // 出栈seqStack. pop( ) ; System. out. println( "出栈后:" ) ; // 遍历栈seqStack. display( ) ; } }
/ **
栈顶元素ghi
出栈后:
def abc * /
二,链栈
2.1,存放数据的结点
public class Node { public Object data; public Node next; public Node ( ) { this ( null, null) ; } public Node ( Object data) { this ( data, null) ; } public Node ( Object data, Node next) { this . data = data; this . next = next; }
}
2.2,链栈的实现
public class LinearStack implements IStack { private Node top; @Override public void clear ( ) { top = null; } @Override public boolean isEmpty ( ) { return top == null; } @Override public int length ( ) { Node p = top; int length = 0 ; while ( p != null) { p = p. next; length ++ ; } return length; } @Override public Object peek ( ) { if ( ! isEmpty ( ) ) return top. data; return null; } @Override public void push ( Object x) { Node s = new Node ( x) ; s. next = top; top = s; } @Override public Object pop ( ) { if ( isEmpty ( ) ) { return null; } Node p = top; top = top. next; return p. data; } @Override public void display ( ) { Node p = top; while ( p != null) { System. out. print ( p. data + "\t" ) ; p = p. next; } } }
2.3测试链栈
public class TestLinearStack { public static void main ( String[ ] args) { LinearStack ls = new LinearStack ( ) ; ls. push ( 1 ) ; ls. push ( 3 ) ; ls. push ( 5 ) ; ls. push ( 7 ) ; System. out. println ( "栈顶元素:" + ls. peek ( ) ) ; System. out. println ( "出栈元素:" + ls. pop ( ) ) ; ls. display ( ) ; } }