/* chain stack A stack implemented with a singly linked list * * */ package com.tulun; public class TestMl2 { public static void main(String[] args) { // TODO Auto-generated method stub LinkStack link=new LinkStack(); for(int i=0;i<10;i++){ link.insertHead(i); } link.show(); link.pop(); link.show(); int a=link.getTop(); System.out.println(a); } } class LinkStack{ class Entry{ int data; Entry next; public Entry(){ this.data = -1; this.next = null; } public Entry(int data){ this.data=data; this.next=null; } } private Entry head=null; public LinkStack(){ this.head=new Entry(); } // Push into the stack and use the head insertion method to make it easier public void insertHead( int val){ Entry entry=new Entry(val); entry.next=head.next; head.next=entry; } // Only the first data node after the first node to pop out of the stack public void pop(){ Entry cur=head.next; if(cur==null){ return; } head.next=cur.next; cur=null; return; } // Get the top element of the stack public int getTop(){ return this .head.next.data; } public void show(){ Entry cur=this.head.next; while(cur!=null){ System.out.println(cur.data); cur=cur.next; } System.out.println(); } }