Down-Stack (linked list implementation):
Import Java.util.iterator;public class Linkedstack<item> implements Iterable<item>{public class Node{Item Item Node Next;} Private Node frist;private int N = 0;public Boolean isEmpty () {return N = = 0;} public int size () {return N;} public void push (item item) {Node Oldfrist = Frist;frist = new Node (); frist.next = Oldfrist;frist.item = Item; n++;} Public Item Pop () {Item item = Frist.item;frist = Frist.next; N--;return item;} @Overridepublic iterator<item> Iterator () {//TODO auto-generated method Stubreturn new Linkedstackiterator ();} Private class Linkedstackiterator implements Iterator<item>{private Node current = frist; @Overridepublic Boolean Hasnext () {//TODO auto-generated method Stubreturn Current! = NULL;} @Overridepublic Item Next () {//TODO auto-generated method Stubitem item = Current.item;current = Current.next;return Item ;} @Overridepublic void Remove () {//TODO auto-generated Method stub}}}
FIFO Queue (linked list implementation):
Import Java.util.iterator;public class Linkedqueue<item> implements Iterable<item>{public class Node{Item Item Node Next;} Private node frist;private node last;private int N = 0;public Boolean isEmpty () {return frist = null;} public int size () {return N;} public void Enqueue (item item) {Node Oldlast = Last;last = new Node (); last.item = Item;last.next = Null;if (IsEmpty ()) {frist = Last;} else {oldlast.next = last;} n++;} Public Item dequeue () {Item item = Frist.item;frist = Frist.next;if (IsEmpty ()) {last = null;} N--;return item;} @Overridepublic iterator<item> Iterator () {//TODO auto-generated method Stubreturn new Linkedqueueiterator ();} Private class Linkedqueueiterator implements Iterator<item>{private Node current = frist; @Overridepublic Boolean Hasnext () {//TODO auto-generated method Stubreturn Current! = NULL;} @Overridepublic Item Next () {//TODO auto-generated method Stubitem item = Current.item;current = Current.next;return Item ;} @Overridepublic void Remove () {//ToDo auto-generated Method stub}}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Algorithm (fourth edition) Java implementation stack and queue for learning notes (linked list implementation)