Size of a linkStack

H

HelpMe

I implemented a linkstack program but was unable to output it's
size.Can anyone help.Please help me soon.My program is:

import java.io.*;
class Link
{
public double data;
public Link next;

public Link(double d)
{ data = d; }

public void displayLink()
{ System.out.print(data + " "); }
}

class LinkList {
Link head;
public LinkList()
{ head = null; }

public boolean isEmpty()
{ return (head==null); }
public void prepend(double d)
{
Link newLink = new Link(d);
newLink.next = head;
head = newLink;
}
public double deleteFirst() {
Link temp = head;
head = head.next;
return temp.data;

}
public void displayList() {
Link current =
head;
while(current != null){
current.displayLink();
current =
current.next; }


System.out.println(""); }
}
class LinkStack
{ private
LinkList
theList;
public
LinkStack()
{
theList = new LinkList();}
public void push(double j){
theList.prepend(j); }
public double pop()
{ return
theList.deleteFirst(); }
public double top() {return
theList.head.data;}
public boolean isEmpty() {return
( theList.isEmpty() ); }
public int size() {
return theList.length; }

public void displayStack()
{ System.out.print("Stack
(top-->bottom): ");
theList.displayList(); }
}
class
LinkStackApp{ public
static void main(String[] args) throws IOException{

LinkStack theStack = new LinkStack();
theStack.push(20);
theStack.push(17);
theStack.displayStack();
theStack.push(60);
theStack.push(80);
theStack.displayStack();
System.out.println("The top element is : "
+theStack.top()); System.out.println("The size of the
stack is : " +theStack.size());
System.out.println("The popped element is : "
+theStack.pop()); theStack.displayStack(); } }
 
G

Gordon Beaton

I implemented a linkstack program but was unable to output it's
size.Can anyone help.Please help me soon.My program is:

You can count the items by iterating over them. You already do
something similar to display the contents.

Or you could store the size in a counter in the LinkList object. Start
at zero, increment for each item you push() and decrement for each
item you pop().

/gordon

--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,054
Latest member
LucyCarper

Latest Threads

Top