LinkedList test - java

public X get(int index)
{
if (index >= 0)
{
Node<X> i = head;
int c = 0;
while (c < index)
{
i = i.getLink();
c++;
}
return i.getValue();
}
else
{
throw new ArrayIndexOutOfBoundsException();
}
}
.
#Test
public void testGet12()
{
LList<String> b = new LList<String>();
b.add("str1");
b.add("str2");
b.add("str3");
b.add("str4");
b.add("str5");
b.add("str6");
b.add("str7");
b.add("str8");
b.add("str9");
b.add("str10");
b.add("str11");
b.add("str12");
assertEquals("str8", b.get(7));
assertEquals("str12", b.get(11));
assertEquals("str1", b.get(0));
}
It is saying that it's expecting str8, but is getting str5, why is my index off by 3? Am i missing something here? To me it seems when it doesnt reach the index it goes up one link until it finally reaches it then spits out the value.

Just an idea
import java.util.ArrayList;
import java.util.List;
public class list {
static List<String> a=new ArrayList<String>();
public String getvalue(int index)
{
return a.get(index);
}
public static void main(String args[]){
list e=new list();
a.add("Str0");
a.add("Str1");
a.add("Str2");
a.add("Str3");
a.add("Str4");
a.add("Str5");
a.add("Str6");
a.add("Str7");
a.add("Str8");
if("Str6".equals(e.getvalue(6))){
System.out.println("true");
}
else
System.out.println("Wrong");
}
}

Related

What is wrong with this code? It won't run

public class StackSimple{
private long capacity=1000;//maximum size of array
private int idx_top;
private Object data[];
public StackSimple(int capacity)
{
idx_top=-1;
this.capacity=capacity;
data = new Object[capacity];
}
public boolean isEmpty(){
return(idx_top<0);
}
public boolean isFull(){
return(idx_top>=capacity-1);
}
public int size()
{
return idx_top+1;
}
public boolean push(Object x){
if (isFull()){
throw new IllegalArgumentException("ERROR:Stack Overflow.Full Stack");
}
else
{`enter code here`data[++idx_top]=x;
return true;
}
}
public Object pop(){
if(isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else{
return data[idx_top--];
}
}
public Object top(){
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else{
return data[idx_top];
}
}
public void print()
{`
for (int i=size()-1;i>=0;i--)
System.out.println(data[i]);
}
}
public class Stack_Exercise {
public static void main(String[] args) {
StackSimple s = new StackSimple(capacity:3);//error shows here
s.push(x:"books");`enter code here`
s.push(x:"something");
s.push(x:"200");
s.print();
System.out.println("Size=" +s.size());
}
}
Why doesn't this work?
Why does it say invalid statement while creating the StackSimple object? The problem is in the main class while running it. There are errors while pushing the elements.
Error while compiling
When passing parameters to a function you just pass the values.
In your case not StackSimple(capacity:3) but just StackSimple(3)
First question, which version of Java are you using.
Second, in Java you should be passing as a variable instead of StackSimple(capacity:3). Change your main method to below, here is my recommendation:
StackSimple s = new StackSimple(3);
s.push("books");
s.push("something");
s.push("200");
s.print();
System.out.println("Size=" +s.size());
You are not at all pushing the value in the stack, your pusch function is not working as it is expected to work.
Here is the correct program.
class StackSimple {
private long capacity = 1000;// maximum size of array
private int idx_top;
private Object data[];
public StackSimple(int capacity) {
idx_top = -1;
this.capacity = capacity;
data = new Object[capacity];
}
public boolean isEmpty() {
return (idx_top < 0);
}
public boolean isFull() {
return (idx_top >= capacity - 1);
}
public int size() {
return idx_top + 1;
}
public boolean push(Object x) {
if (isFull()) {
throw new IllegalArgumentException("ERROR:Stack Overflow.Full Stack");
} else {
data[++idx_top] = x;
return true;
}
}
public Object pop() {
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else {
return data[idx_top--];
}
}
public Object top() {
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else {
return data[idx_top];
}
}
public void print() {
for (int i = size() - 1; i >= 0; i--)
System.out.println(data[i]);
}
}
public class test {
public static void main(String[] args) {
StackSimple s = new StackSimple(3);// error shows here
s.push("books");
s.push("something");
s.push("200");
s.print();
System.out.println("Size=" + s.size());
}
}

Reverse a stack using only queue in Java?

I need to loop through the stack until it is empty, adding each element to the queue. Then do the opposite. Loop through the queue until it is empty, adding each element back onto the stack
public class Q1 {
public static void reverseStack(Stack st){
}
}
Here is my test:
public class Q1Test {
#Test
public void testQ1() {
Stack st = new Stack(5);
st.push("A");
st.push("B");
Q1.reverseStack(st);
assertEquals("A",(String) st.top());
}
}
I have been trying to do the Q1 code and never get it to succeed and always end up fail. Can anyone implement a methods as said above to make the Q1 test succeed please?
Here is a working example:
Q1.java
import java.util.ArrayList;
import java.util.List;
public class Q1 {
private List<String> list;
public Q1() {
list = new ArrayList<String>();
}
public String pop_front() {
if (!list.isEmpty()) {
String front = list.get(0);
for (int i = 0; i < list.size()-1; i++) {
list.set(i, list.get(i+1));
}
list.remove(list.size()-1);
return front;
} else {
return null;
}
}
public void push_back(String obj) {
list.add(obj);
}
public String front() {
if (!list.isEmpty()) {
return list.get(0);
} else {
return null;
}
}
public boolean isEmpty() {
return list.isEmpty();
}
public static void reverseStack(Stack stack) {
Q1 queue = new Q1();
while (!stack.isEmpty()) {
queue.push_back(stack.pop());
}
while (!queue.isEmpty()) {
stack.push(queue.pop_front());
}
}
}
A Stack class:
Stack.java
package com.dub;
import java.util.ArrayList;
import java.util.List;
public class Stack {
private List<String> list;
public Stack() {
list = new ArrayList<String>();
}
public String pop() {
if (!list.isEmpty()) {
String top = list.get(list.size()-1);
list.remove(list.size()-1);
return top;
} else {
return null;
}
}
public void push(String obj) {
list.add(obj);
}
public String top() {
if (!list.isEmpty()) {
return list.get(list.size()-1);
} else {
return null;
}
}
public boolean isEmpty() {
return list.isEmpty();
}
}
and now the test method:
public static void main(String[] args) {
Stack stack = new Stack();
stack.push("A");
stack.push("B");
stack.push("C");
System.out.println("top: " + stack.top());
Q1.reverseStack(stack);
System.out.println("top: " + stack.top());
}
It prints as expected:
top: C
top: A

Made a Priority Queue, having problems with delMin and insert

I have made a Priority Queue class with an array list, but I am having trouble with the insert and delMin (delete minimum areas). I cannot create more functions and here is my code:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class MyMinPQ<E extends Comparable<E>> implements Iterable<E> {
private ArrayList<E> pq;
private int N;
public MyMinPQ() {
pq = new ArrayList<E>();
}
public E delMin(){
E minVal = min();
pq.remove(0);
N--;
return minVal;
}
public E min (){
if (isEmpty())
throw new NoSuchElementException();
return pq.get(0);
}
public void insert (E item){
for (int i = 0; i < N; i++){
pq.add(item);
if (pq.get(i) > pq.get(i+1)) {
E tmp = pq.get(i);
pq.set(i+1, tmp);
}
}
N++;
}
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
public Iterator<E> iterator() {
return new Iterator<E>(){
int current = 0;
public boolean hasNext() {
return current != size();
}
public E next() {
if (hasNext())
return pq.get(current++);
else throw new NoSuchElementException( );
}
public void remove() {
throw new UnsupportedOperationException( );
}
};
}
}
At the insert portion of the code, I know that I have to sort the new additions to Arraylist but I am having issues with going about this. I tried to compare the values that is within the list, but eclipse does not allow it based on how I formatted it. When I use compareTo, it does not work with my iterator and everything goes into disarray.
My question is how can I go about modifying my insert function so it can sort new items in descending order? Will my delMin() also have to change because of it?
try this
public void insert(E item) {
int i = 0;
while (i < N && pq.get(i).compareTo(item) <= 0) {
i++;
}
N++;
}

Inexplicable Issue with Add Method of a Simple Binary Tree

My binary tree looks pretty close to my class materials, but when I print to the console or check for contains(), any adds I'm doing aren't registered.
I don't have a great understanding of static and the debugger is giving me a hint about making a static reference to non-static variable overallRoot, but everything compiles without error or warning in eclipse.
public class BSTSimpleSet<E extends Comparable<E>> implements SimpleSet<E> {
private GTNode<E> overallRoot;
private int size;
public static void main(String[] args) {
BSTSimpleSet<Integer> main = new BSTSimpleSet<Integer>(2);
main.toString();
main.add(3);
main.toString();
main.add(4);
main.toString();
main.add(5);
main.toString();
System.out.print(main.contains(3));
}
public BSTSimpleSet() {
size = 0;
}
public BSTSimpleSet(E input) {
overallRoot = new GTNode<E>(input);
size = 1;
}
public boolean add(E e) {
return add(e, overallRoot);
}
private boolean add(E e, GTNode<E> root) {
if (root == null) {
root = new GTNode<E>(e);
size++;
return true;
} else {
int compare = e.compareTo(root.data);
if (compare == 0) {
return false;
} else if (compare < 0) {
return add(e, root.left);
} else {
return add(e, root.right);
}
}
}
public void clear() {
overallRoot = null;
}
public boolean contains(E e) {
return contains(e, overallRoot);
}
private boolean contains(E e, GTNode<E> root) {
if (root == null) {
return false;
} else {
int compare = e.compareTo(root.data);
if (compare == 0) {
return true;
} else if (compare < 0) {
return contains(e, root.left);
} else {
return contains(e, root.right);
}
}
}
public boolean isEmpty() {
if (overallRoot == null) {
return false;
} else {
return true;
}
}
public int size() {
return size;
}
public String toString() {
this.toString(overallRoot, 0);
return null;
}
private void toString(GTNode<E> root, int level) {
if (root != null) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println(root.data);
toString(root.left, level + 1);
toString(root.right, level + 1);
} else {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println("_");
}
}
private static class GTNode<E extends Comparable<E>> {
public E data;
public GTNode<E> left;
public GTNode<E> right;
public GTNode(E input) {
this(input, null, null);
}
public GTNode(E input, GTNode<E> lNode, GTNode<E> rNode) {
data = input;
left = lNode;
right = rNode;
}
}
}
This code does absolutely nothing.
private boolean add(E e, GTNode<E> root) {
if (root == null) {
root = new GTNode<E>(e);
size++;
return true;
}
...
Java passes in the Object Reference to a method. If you change the Reference, that will not
be propagated back to the calling method. If you change what the Reference refers to
that will be propagated back.
eg
// arrays behave the same way so using them to illustrate.
public void callMethods(){
int[] array = new int[1];
array[0] = 0;
doesNotChange(array);
System.out.println(array[0]);// will print 0
doesAChange(array);
System.out.println(array[0]);// will print 1
}
public void doesNotChange(int[] myArray){
myArray = new int[1];
myArray[0] = 1;
}
public void doesAChange(int[] myArray){
myArray[0] = 1;
}
To avoid these sorts of things I recommend always setting method parameters final.
The GTNode class shouldn't be static. Static classes are classes with only static methods, which means they don't have to be instantiated. The prototypical example of this is the java.lang.Math class: You don't need to call something like Math m = new Math(); m.cos(); to get the cosine, you just call Math.cos(). Since you're creating multiple instances of the GTNode class, make it non-static and you should be good.

stack generic class not working [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java how to: Generic Array creation
import java.util.EmptyStackException;
import java.util.Vector;
public class Stack<E> extends Vector<E> {
private E a[];
private int top;
public void Stack() {
a = new E[100];
top = -1;
}
public void Stack(int n) {
a = new E[n];
top = -1;
}
public E pop() {
E obj;
int len = size();
if (top == -1)
throw new EmptyStackException();
else
obj = a[top--];
return obj;
}
public void push(E e) {
if (e == null)
throw new NullPointerException();
else if (top == size() - 1)
System.out.println("Stack full");
else {
a[++top] = e;
System.out.println("pushed :" + e);
}
}
public int size() {
int i;
for (i = 0; a[i] != null; i++)
;
return i;
}
}
This is my stack generics class in java. I am getting an error in array declaration inside the two constructor i.e Stack() and Stack(int n). The error is "generic array creation" in both cases. please help
generic array is can not be created. so use Object array.
import java.io.*;
import java.util.EmptyStackException;
import java.util.Vector;
public class Stack extends Vector
{
private Object a[];
private int top;
public void Stack()
{
a=new Object[100];
top=-1;
}
public void Stack(int n)
{
a=new Object[n];
top=-1;
}
public E pop()
{
E obj;
int len = size();
if (top == -1)
throw new EmptyStackException();
else
obj=(E) a[top--];
return obj;
}
public void push(E e)
{
if(e==null)
throw new NullPointerException();
else if(top==size()-1)
System.out.println("Stack full");
else
{
a[++top]=e;
System.out.println("pushed :"+e);
}
}
public int size()
{
int i;
for(i=0;a[i]!=null;i++);
return i;
}
}
You do not have constructors in your class these are methods. for construtors remove the void type. Constructors don't have return types. Also your class name starts with lower letter stack and constructors start with Stack . Rename your class to Stack and remove void types.
You need to do it like this
public Stack(Class<E> cls)
{
a = (E[]) Array.newInstance( cls);
top=-1;
}
public Stack(Class<E> cls,int n)
{
a = (E[]) Array.newInstance( cls,n);
top=-1;
}
see Generic Array
Following is your working class with object creation in main method.
class Stack<E> extends Vector<E> {
private E a[];
private int top;
public Stack(Class<E> cls)
{
a = (E[]) Array.newInstance( cls);
top=-1;
}
public Stack(Class<E> cls,int n)
{
a = (E[]) Array.newInstance( cls,n);
top=-1;
}
public E pop() {
E obj;
int len = size();
if (top == -1)
throw new EmptyStackException();
else
obj = a[top--];
return obj;
}
public void push(E e) {
if (e == null)
throw new NullPointerException();
else if (top == size() - 1)
System.out.println("Stack full");
else {
a[++top] = e;
System.out.println("pushed :" + e);
}
}
public int size() {
int i;
for (i = 0; a[i] != null; i++)
;
return i;
}
public static void main(String...strings ){
Stack<Integer> st=new Stack<Integer>(Integer.class,n);
}
}

Categories