I am new to Generics in java and I really need help in this code
it is not compiling i dont know why!
The stack class is:
public class GenericStack<Item>{
public class Stack {
private Node first=null;
private class Node {
Item item;
Node next;
}
public boolean IsEmpty()
{
return first==null;
}
public void push (Item item)
{
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
}
public Item pop ()
{
Item item=first.item;
first=first.next;
return item;
}
}
}
and here is the main
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
GenericStack<Integer> ob = new GenericStack<Integer>();
ob.push(5);
obpush(10);
ob.push(15);
while (!ob.IsEmpty())
{
int x=ob.pop();
StdOut.print(x);
}
}
}
now the error is:
The method push(int) isn't defined for the type GenericStack<Integer>
Where did i go wrong?! can anyone explain please to me
Thank you in advance
Your GenericStack class has no methods. Get rid of the nested class structure and use the generic type parameter for Stack directly:
public class Stack<Item> {
private Node first=null;
private class Node {
Item item;
Node next;
}
public boolean IsEmpty()
{
return first==null;
}
public void push (Item item)
{
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
}
public Item pop ()
{
Item item=first.item;
first=first.next;
return item;
}
}
class GenericStack<Item>{
class Stack {
private Node first=null;
private class Node {
Item item;
Node next;
}
public boolean IsEmpty()
{
return first==null;
}
public void push (Item item)
{
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
}
public Item pop ()
{
Item item=first.item;
first=first.next;
return item;
}
}
}
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
GenericStack<Integer> ob = new GenericStack<Integer>();
GenericStack<Integer>.Stack st=ob.new Stack();
st.push(5);
st.push(10);
st.push(15);
while (!st.IsEmpty())
{
int x=st.pop();
// StdOut.print(x);
System.out.println(x);
}
}
}
You are calling methods of the inner class. So that using object of outer class you cannot directly call the methods of the inner class. See above code for that.
Hope this helps.
Because method push is defined in class GenericStack.Stack, not GenericStack. To make it work replace
GenericStack<Integer> ob = new GenericStack<Integer> ();
with
GenericStack<Integer>.Stack ob = new GenericStack.Stack ();
The main issue with your code is that you mixed 2 public classes, just changed a little your code, have fun !!
GenericStack.java
public class GenericStack<Item> {
private Node first = null;
private class Node {
Item item;
Node next;
}
public boolean IsEmpty() {
return first == null;
}
public void push(Item item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
}
public Item pop() {
Item item = first.item;
first = first.next;
return item;
}
}
TestGenericStack.java
public class TestGenericStack {
public static void main(String[] args) {
GenericStack<Integer> ob = new GenericStack<Integer>();
ob.push(5);
ob.push(10);
ob.push(15);
while (!ob.IsEmpty()) {
int x = ob.pop();
System.out.println(x);
}
}
}
Get rid of the extra coating of class Stack from GenericStack.
Thanks!
Related
So I´m trying to code the basics of a stack data structure and when I run the class in sample_stack it´s simply not running and not printing the words and instead just printing "null" :( does anyone know why? apologies if this is obvious
STACK JAVA CLASS:
import java.util.NoSuchElementException;
public class Stack {
// private inner class node
private class Node{
private String item;
private Node link;
public Node() {
item = null;
link = null;
}
public Node(String item, Node link) {
item = this.item;
link = this.link;
}
} // end of inner class
private Node head;
public Stack() {
head = null;
}
// method: PUSH into stack (like addToStart)
public void push(String itemName) {
head = new Node(itemName, head); // so head is the top of the stack ????
}
// method: POP out of stack
public String pop() {
if (head == null) throw new IllegalStateException();
else {
String returnItem = head.item;
head = head.link; // the second top item becomes the new head
return returnItem;
}
}
// method: is it empty?
public boolean isEmpty() {
return ( head == null );
}
}
CLASS USING THE STACK JAVA CLASS:
public class Stack_Example {
public static void main (String[] args) {
Stack message = new Stack();
message.push("Hi");
System.out.println(message.pop());
message.push("my");
message.push("name");
message.push("is");
message.push("JARVIS");
while (!message.isEmpty()) { // while true
String s = message.pop();
System.out.println(s);
}
}
}
Thank you in advance!
public void push(String itemName) {
head = new Node(itemName, head); // so head is the top of the stack ????
}
head is null when you call the constructor, and so the link here, public Node(String item, Node link) { is always null
Don't you want,
public void push(String itemName) {
head = new Node(itemName, this);
}
instead?
Also, this is backwards:
public Node(String item, Node link) {
item = this.item;
link = this.link;
}
It should be:
public Node(String item, Node link) {
this.item = item;
this.link = link;
}
More importantly, you should be debugging all of this as you go along
i have a problem that the method in LinkedList class don't print anything.. and i'm trying hard to know what's the problem i hope someone help
the main class
public static void main(String[] args) {
LLnode a = new LLnode(10);
LLnode b = new LLnode(20);
LLnode c = new LLnode(50);
LinkedList List1 = new LinkedList();
List1.printAllNodes();
}
}
LinkedList class
public class LinkedList {
private LLnode head;
public LLnode gethead() {
return this.head;
}
public void sethead(LLnode LLnode) {
this.head = LLnode;
}
// Constructor
public LinkedList() {
head = null;
}
// Example Method to check if list is empty
public boolean isEmpty() {
return head == null;
}
public void printAllNodes() {
LLnode helpPtr = head;
while (helpPtr != null) {
System.out.print(helpPtr.getdata() + " ");
helpPtr = helpPtr.getnext();
}
why it dosn't print i tried so hard
This is because you never add any nodes to your LinkedList.
Code could be as follows. Beware, nodes will be added at the beginning of list.
Main class:
public static void main(String[] args) {
LLnode a = new LLnode(10);
LLnode b = new LLnode(20);
LLnode c = new LLnode(50);
LinkedList List1 = new LinkedList();
List1.add(a).add(b).add(c);
List1.printAllNodes();
}
}
LinkedList class:
public class LinkedList {
private LLnode head;
public LLnode gethead() {
return this.head;
}
public void sethead(LLnode LLnode) {
this.head = LLnode;
}
// Constructor
public LinkedList() {
head = null;
}
// Example Method to check if list is empty
public boolean isEmpty() {
return head == null;
}
public LinkedList add(LLnode node){
LLnode oldHead = this.head();
this.head = node;
node.setNext(oldHead);
return this;
}
public void printAllNodes() {
LLnode helpPtr = head;
while (helpPtr != null) {
System.out.print(helpPtr.getdata() + " ");
helpPtr = helpPtr.getnext();
}
}
Recently,I'm learing the Algorithms 4th,when I come to solve the problem that
Create a new constructor for the linked-list implementation of Stack.java so that Stack t = new Stack(s) makes t reference a new and independent copy of the stack s.
Here is the Stack.java
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Stack<Item> implements Iterable<Item> {
private Node<Item> first; // top of stack
private int n; // size of the stack
private static class Node<Item> {
private Item item;
private Node<Item> next;
}
/**
* Initializes an empty stack.
*/
public Stack() {
first = null;
n = 0;
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return n;
}
public void push(Item item) {
Node<Item> oldfirst = first;
first = new Node<Item>();
first.item = item;
first.next = oldfirst;
n++;
}
public Item pop() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
Item item = first.item; // save item to return
first = first.next; // delete first node
n--;
return item; // return the saved item
}
private class ListIterator<Item> implements Iterator<Item> {
private Node<Item> current;
public ListIterator(Node<Item> first) {
current = first;
}
public boolean hasNext() {
return current != null;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}
The answer of Recursive solution is that create a copy constructor for a linked list starting at a given Node and use this to create the new stack.
Node(Node x) {
item = x.item;
if (x.next != null) next = new Node(x.next);
}
public Stack(Stack<Item> s) { first = new Node(s.first); }
But what make me confused is how can I combine the above code to the Stack.java as its constuctor,how can I handle the Node? to create a new class Node??May someone could hep me:)
You don't need to create a new class Node. The Node is the same for the old stack and the new stack 't'.
Currently you have one constructor in your Stack class public Stack(). You need to make another one that accepts a Stack, as you've done in your example, which then calls a method that copies the old elements to the new stack (recursively or iteratively). It sounds like homework so I don't think any code is appropriate (not sure of the rules in that regard).
Here is the code fragment I hava solved my problem
private class Node{
Item item;
Node next;
Node() { } //default constructor Node
Node(Node x){
item=x.item;
if(x.next!=null) next=new Node(x.next);
}
}
public Stack(){ //default constructor Stack
first=null;
N=0;
}
public Stack(Stack<Item> s) {first=new Node(s.first); }
My java class comps up with a NullPointerException.Please help!
The error messages:
java.lang.NullPointerException at
RandomizedQueue.dequeue(52 line) at
RandomizedQueue$IndependantIterator.next (88 line) at
RandomizedQueue.main (104)
I have signed the line number in the end of the error code line.
import java.util.Iterator;
public class RandomizedQueue<Item> implements Iterable<Item> {
private int number=0;
private Node first=null;
private Node end=null;
private class Node {
Item item;
Node next=null;
Node last=null;
}
private Node Random() {
double r = Math.random();
int n = (int) (r*number);
if(n==0) n=1;
Node ob=first;
for(int i=0;i<(n-1);i++) {
ob = ob.next;
}
return ob;
}
public RandomizedQueue() {
Node empty=new Node();
}
public boolean isEmpty() {
return number==0;
}
public int size() {
return number;
}
public void enqueue(Item item) {
if(item==null) throw new NullPointerException();
number++;
if(first==null) {
first = new Node();
end = first;
first.item = item;
}
else {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
oldfirst.last = first;
}
}
public Item dequeue() {
Node ob=Random();
Item back=ob.item;
if(ob==end) {
end = ob.last;
ob.last.next=null; //52 line
}else if(ob==first) {
first=first.next;
first.last=null;
}
else {
ob.last.next=ob.next;
ob.next.last=ob.last;
}
return back;
}
public Node sample() {
return Random();
}
public Iterator<Item> iterator() {
return new IndepentRandomIterator();
}
private class IndepentRandomIterator implements Iterator<Item> {
private RandomizedQueue<Item> iq = new RandomizedQueue<Item>();
Node scan = first;
public IndepentRandomIterator() {
while(scan != null) {
iq.enqueue(scan.item);
scan=scan.next;
}
}
public boolean hasNext() {
return iq.number >0;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if(iq.number==0) throw new java.util.NoSuchElementException();
return iq.dequeue(); //88
}
}
public static void main(String[] args) {
RandomizedQueue<String> test = new RandomizedQueue<String>();
test.enqueue("Luo");
test.enqueue("Jiebin");
test.enqueue("is");
test.enqueue("genious");
test.dequeue();
test.dequeue();
StdOut.println("Is it empty?"+test.isEmpty());
StdOut.println("Size: "+test.size());
StdOut.println("A sample: "+test.sample());
Iterator<String> it = test.iterator();
while(it.hasNext()) {
String s = it.next(); //104
}
}
}
It's because ob.last is null. The only time that end is set is when item is first in enqueue(). And last is never set there. In dequeue(), it goes to the if block if ob == end. Since end.last == null, therefore ob.last == null too and ob.last.next will throw NPE.
Can someone explain what am I doing wrong here ?
I am trying to create a queue from two stacks as per a book exercise. I get error "Stack Underflow" from the peek function. But everything seems right to me :P Please explain. Thanks!
//Program to implement Queue using two Stacks.
import java.util.NoSuchElementException;
public class Ex3_5_Stack {
int N;
int countOfNodes=0;
private Node first;
class Node {
private int item;
private Node next;
}
public Ex3_5_Stack() {
first=null;
N=0;
}
public int size() {
return N;
}
public boolean isEmpty() {
return first==null;
}
public void push(int item){
if (this.countOfNodes>=3) {
Ex3_5_Stack stack = new Ex3_5_Stack();
stack.first.item=item;
N++;
} else {
Node oldfirst = first;
first = new Node();
first.item=item;
first.next=oldfirst;
N++;
}
}
public int pop() {
if (this.isEmpty())
throw new NoSuchElementException("Stack Underflow");
int item = first.item;
first=first.next;
return item;
}
public int peek() {
if (this.isEmpty())
throw new NoSuchElementException("Stack Underflow");
return first.item;
}
}
And MyQueue file
public class Ex3_5_MyQueue {
Ex3_5_Stack StackNewest,StackOldest;
public Ex3_5_MyQueue() {
super();
StackNewest = new Ex3_5_Stack();
StackOldest = new Ex3_5_Stack();
}
public int size() {
return StackNewest.size()+StackOldest.size();
}
public void add(int value) {
StackNewest.push(value);
}
private void transferStack() {
if (StackOldest.isEmpty()) {
while (StackNewest.isEmpty()) {
StackOldest.push(StackNewest.pop());
}
}
}
public int peek() {
this.transferStack();
return StackOldest.peek();
}
public int remove() {
this.transferStack();
return StackOldest.pop();
}
public static void main(String[] args) {
Ex3_5_MyQueue myQueue = new Ex3_5_MyQueue();
myQueue.add(4);
myQueue.add(3);
myQueue.add(5);
myQueue.add(1);
System.out.println(myQueue.peek());
}
}
In transferStack(), you're missing an exclamation mark. It should be:
private void transferStack(){
if(StackOldest.isEmpty()){
while(!StackNewest.isEmpty()){ // you forgot it here
StackOldest.push(StackNewest.pop());
}
}
}