I'm still learning how to use LinkedList, in my CSCI 1302 course, correctly so let me know if I am doing something wrong. I want to implement a stack data structure using the operations push() and pop(). I still need to build the driver class, but I was hoping someone could show me where I could implement these two operations within my code.
import java.util.*;
public class myStack {
private class Node
{
public int data;
public Node next;
public Node(int data)
{
next = null;
this.data = data;
}}
public LinkedDesign() //Linkedlist constructor
{
head = null;
}
public void add(int keydata) //add new value to the end of linked list
{
Node temp = new Node(keydata);
Node current = head;
if(head == null)
head = temp;
else
{
while(current.next != null)
{
current = current.next;
}
current.next = temp;
}
}
public void print()
{
// from head to tail, print each node's data
for (Node current = head; current != null; current = current.next)
{
System.out.print(current.data + " ");
}
System.out.println();
}
// toString(): print data in the linked list
public String toString()
{
Node current = head;
String output = "";
while(current != null)
{
output += "[" + current.data + "]";
current = current.next;
}
return output;
}
}
Please login or Register to submit your answer