Stack: LIFO LIFO
Life Example: Advanced elevator after the coming out
The basic structure of the storage element:
Public class The Node {/* element has two parts: the element's value is the next element's reference */ Object data; // data fields // pointer field Public Node () {} Public Node (Object data,node next) { this. data=data; this. next=next;} }
Implementation stack:
/*** Created by yaming * Stack chain storage*/ Public classlinkstack{PrivateNode top;//Stack Top element Private intSize//Current stack size PublicLinkstack () {Top=NULL; } /*** The size of the current stack *@return */ Public intLength () {returnsize; } /*** Determine if the stack is empty *@return */ Public BooleanIsEmpty () {returnSize==0?true:false; } /*** into the stack *@paramData *@return */ Public Booleanpush (Object data) {node node=NewNode (data,NULL); if(IsEmpty ()) {Top=node; }Else{Node.next=top;//Put the element on top of the stack, referring to the top of the stacktop=node; } size++;//element into the stack, the top of the stack rises return true; } /*** out of the stack *@return */ PublicObject Pop () {if(IsEmpty ()) {return NULL; }Else{Node value=top;//get top of stack elementTop=top.next;//Update head nodevalue.next=NULL;//The reference to the top element of the stack is set to NULL, and the element is recycledsize--; returnValue.data;//the elements of the stack } } /*** Returns the top element of the stack *@return */ PublicObject Peek () {if(IsEmpty ()) {return NULL; } returnTop.data; } /*** Traversal Stack *@return */ PublicString Stack () {if(IsEmpty ()) {return"[]"; }Else{StringBuilder StringBuilder=NewStringBuilder ("["); for(Node current=top;current!=NULL; current=Current.next) {Stringbuilder.append (current.data.toString ()+", "); } intLength=stringbuilder.length (); returnStringbuilder.delete (Length-2,length). Append ("]"). toString (); } } Public voidClear () {Top=NULL; Size=0; }}
Stack--java Implementation