1 //implementing stacks with linked lists2 /**3 * Node class4 */5 classLinkS {6 Private Longdata;7 PublicLinkS Next;8 9 PublicLinkS (Longd) {Ten This. data =D; One } A - PublicString toString () { - returnstring.valueof (data); the } - } - - /** + * Chain List class - */ + classLinkslist { A PrivateLinkS first; at - Publiclinkslist () { -First =NULL; - } - - Public voidInsertfirst (LinkS node) { inNode.next =First ; -First =node; to } + - PublicLinkS Deletefirst () { theLinkS temp =First ; *First =First.next; $ returntemp;Panax Notoginseng } - the Public BooleanIsEmpty () { + returnFirst = =NULL; A } the + PublicString toString () { - if(IsEmpty ()) $ return"[]"; $StringBuilder SB =NewStringBuilder (); -Sb.append ("["); -LinkS Curr =First ; the while(Curr! =NULL) { -Sb.append (Curr.tostring ()). Append (",");WuyiCurr =Curr.next; the } -Sb.deletecharat (Sb.length ()-1); WuSb.append ("]"); - returnsb.tostring (); About } $ } - - /** - * Stack A */ + classLinkstack { the Privatelinkslist linklist; - $ PublicLinkstack () { the This. linklist =Newlinkslist (); the } the the Public voidpush (LinkS l) { - This. Linklist.insertfirst (l); in } the the PublicLinkS Pop () { About return This. Linklist.deletefirst (); the } the the Public BooleanIsEmpty () { + return This. Linklist.isempty (); - } the Bayi PublicString toString () { the return This. linklist.tostring (); the } - - Public voiddisplay () { the System.out.println (toString ()); the } the } the - Public classLinkstackdemo { the Public Static voidMain (string[] args) { theLinkstack stack =NewLinkstack (); the for(inti = 0; I < 5; i++) {94LinkS L =NewLinkS (i); the Stack.push (l); the Stack.display (); the }98 while(!Stack.isempty ()) { AboutSystem.out.print ("Pop out" +Stack.pop ()); -System.out.print ("Now Stack is:");101 Stack.display ();102 }103 }104}
Java data structure and algorithms note-ch5-List-4 implementing a stack with a linked list