Source: Internet
Author: User
Tags assert

#Sentinel node


# Reference Code, note import two libraries


/****************************************************************************** * Compilation:javac * Execution:java Linkedstack < Input.txt * * Data files: Https://* * A generic stack, implemented using A linked list. Each of the stack * element is of type Item. * *% more tobe.txt * to being or not to-be--that--is * * *% java linkedstack < Tobe.txt * Or is (2 left on stack) * ******************************************************************************/ImportEdu.princeton.cs.algs4.StdOut;Importedu.princeton.cs.algs4.StdIn;ImportJava.util.Iterator;Importjava.util.NoSuchElementException;/*** The {@codeLinkedstack} class represents a Last-in-first-out (LIFO) stack of * generic items. * It supports the usual <em>push</em> <em>pop</em> operations, along with methods * for Peek ing at the top item, testing if the stack was empty, and iterating through * the items in LIFO order. * <p> * This implementation uses a singly linked list with a non-static nested class for * linked-list nodes. See {@linkStack} for a version that uses a static nested class. * the <em>push</em>, <em>pop</em>, <em>peek</em>, <em>size</em>, and <em>is-empty</em> * Operations all take constant time in the worst case. * <p> * For additional documentation, * see <a href= "Https://">section 1.3</a> of * <i>algorithms, 4th edition</i> by Robert Sedgewick and Kevin Wayne. * *  @authorRobert Sedgewick *@authorKevin Wayne*/ Public classLinkedstack<item>ImplementsIterable<item> {    Private intN//size of the stack    PrivateNode first;//Top of Stack//Helper Linked List class    Private classNode {Privateitem Item; PrivateNode Next; }    /*** Initializes an empty stack. */     PublicLinkedstack () { First=NULL; N= 0; assertcheck (); }    /*** Is this stack empty? * @returntrue if this stack is empty; false otherwise*/     Public BooleanIsEmpty () {returnFirst = =NULL; }    /*** Returns the number of items in the stack. * @returnThe number of items in the stack*/     Public intsize () {returnN; }    /*** Adds The item to this stack. * @paramitem the item to add*/     Public voidpush (item item) {Node Oldfirst=First ; First=NewNode (); First.item=item;; N++; assertcheck (); }    /*** Removes and returns the item most recently added to this stack. * @returnThe item most recently added *@throwsjava.util.NoSuchElementException If this stack is empty*/     PublicItem Pop () {if(IsEmpty ())Throw NewNosuchelementexception ("Stack underflow"); Item Item= First.item;//Save item to returnfirst =;//Delete First noden--; assertcheck (); returnItem//return the saved item    }    /*** Returns (but does not remove) the item is the recently added to this stack. * @returnThe item most recently added to this stack *@throwsjava.util.NoSuchElementException If this stack is empty*/     PublicItem Peek () {if(IsEmpty ())Throw NewNosuchelementexception ("Stack underflow"); returnFirst.item; }    /*** Returns A string representation of this stack. * @returnthe sequence of items in the stack in LIFO order, separated by spaces*/     PublicString toString () {StringBuilder s=NewStringBuilder ();  for(Item Item: This) S.append (item+ " "); returns.tostring (); }           /*** Returns An iterator to this stack, that iterates through, the items in LIFO order. * @returnAn iterator to this stack, the iterates through the items in LIFO order. */     PublicIterator<item>iterator () {return NewListiterator (); }    //An iterator, doesn ' t implement remove () since it ' s optional    Private classListiteratorImplementsIterator<item> {        PrivateNode current =First ;  Public BooleanHasnext () {returnCurrent! =NULL; }         Public voidRemove () {Throw Newunsupportedoperationexception (); }         PublicItem Next () {if(!hasnext ())Throw Newnosuchelementexception (); Item Item=Current.item;; returnitem; }    }    //Check internal invariants    Private BooleanCheck () {//check a few properties of instance variable ' first '        if(N < 0) {            return false; }        if(n = = 0) {            if(First! =NULL)return false; }        Else if(n = = 1) {            if(First = =NULL)return false; if(! =NULL)return false; }        Else {            if(First = =NULL)return false; if( = =NULL)return false; }        //Check internal consistency of instance variable n        intNumberofnodes = 0;  for(Node x = first; X! =NULL&& numberofnodes <= N; x {numberofnodes++; }        if(Numberofnodes! = N)return false; return true; }    /*** Unit tests the {@codelinkedstack} data type. *     * @paramargs the command-line arguments*/     Public Static voidMain (string[] args) {Linkedstack<String> stack =NewLinkedstack<string>();  while(!Stdin.isempty ()) {String Item=stdin.readstring (); if(!item.equals ("-") ) Stack.push (item); Else if(!Stack.isempty ()) Stdout.print (Stack.pop ()+ " "); } stdout.println ("(" + stack.size () + "left on stack)"); }}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.