turning pointer to LinkedList of ArrayList into String - java

I'm trying to make a linkedList (elements) of custom arrayList (coordinated )that with type Object
the Output I am looking for is
Arraylist1 coord1 [2,5,1]
Arraylist2 coord2 [7,6,9]
LinkedList List1 [[2,5,1],[7,6,9]]
this is my output
[ 2 5 1 ]
[ 7 6 9 ]
assignment1.arrayList#33909752
assignment1.arrayList#55f96302
I tried using toString method with no luck
can someone please explain to me how to print the output with no pointers to memory.
and do I need a method to access a specific element in a certain position (in the linkList) and get its coordinates?
here is my code:
thanks
public class arrayList {
private Object[] myList;
private int counter = 0;
private int capacity = 100;
public arrayList() {
myList = new Object[this.capacity];
}
public Object get(int index) {
if (index < counter) {
return myList[index];
} else {
throw new ArrayIndexOutOfBoundsException();
}
}
public void add(Object obj) {
myList[counter++] = obj;
}
public Object remove(int index) {
if (index < counter) {
Object obj = myList[index];
int temp = index;
myList[index] = null;
while (temp < counter) {
myList[temp] = myList[temp + 1];
myList[temp + 1] = null;
temp++;
}
counter--;
return obj;
} else {
throw new ArrayIndexOutOfBoundsException();
}
}
public int size() {
return counter;
}
public void display(Object obj1) {
System.out.print("[");
for (int i = 0; i < this.size(); i++) {
System.out.print(" " + this.get(i) + " ");
}
System.out.print("]");
System.out.println();
}
}
public class linkedList {
public Cube firstLink;
public Cube next;
linkedList() {
firstLink = null;
}
public void insertFirstLink(Object e) {
Cube newLink = new Cube(e);
newLink.next = firstLink;
firstLink = newLink;
}
public boolean isEmpty() {
return (firstLink == null);
}
public Cube removeFirst() {
Cube linkReference = firstLink;
if (!isEmpty()) {
firstLink = firstLink.next;
} else {
System.out.println("Empty Linked list!");
}
return linkReference;
}
public void display() {
Cube theLink = firstLink;
while (theLink != null) {
theLink.display();
theLink = theLink.next;
System.out.println();
}
}
public Cube find(Object obj) {
Cube theLink = firstLink;
if (!isEmpty()) {
while (theLink.obj != obj) {
if (theLink.next == null) {
return null;
} else {
theLink = theLink.next;
}
}
} else {
System.out.println("Empty List!");
}
return theLink;
}
public Cube removeLink(Object obj) {
Cube currentLink = firstLink;
Cube previousLink = firstLink;
while (currentLink.obj != obj) {
if (currentLink.next == null) {
return null;
} else {
previousLink = currentLink;
currentLink = currentLink.next;
}
}
if (currentLink == firstLink) {
firstLink = firstLink.next;
} else {
previousLink.next = currentLink.next;
}
return currentLink;
}
}
public class Cube {
public Object obj;
public Cube next;
public Cube(Object obj) {
this.obj = obj;
}
public void display() {
obj.toString();
System.out.println(obj);
}
public static void main(String[] args) {
arrayList coord1 = new arrayList();
coord1.add(new Integer(2));
coord1.add(new Integer(5));
coord1.add(new Integer(1));
arrayList coord2 = new arrayList();
coord2.add(new Integer(7));
coord2.add(new Integer(6));
coord2.add(new Integer(9));
coord1.display(coord1);
coord2.display(coord2);
linkedList position1 = new linkedList();
position1.insertFirstLink(coord1);
position1.insertFirstLink(coord2);
position1.display();
}
}

According to the API, https://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println(java.lang.Object)
You put a Object into System.out.println(x) will eventually call String.valueOf(x) which utlimitly call x.toString(). Put this #1
In linkedList.display() it will call Cube.display(). Cube.display() will prints its encapsulated object. The object turns out to be an arrayList. From #1, the method call would become arrayList.toString(). However, arrayList did not implement toString(). Don't worry, Java got your back. Since all non-primitive type extends Object, arrayList will has is toString() method inherited from Object. This is the Object implementation, to print the object id. If you don't like it, you can define your own toString() in arrayList scope.
Update 1
You may wonder why the first arraylist could print something meaningful out. It is because you call its arraylist.display() directly, not System.out.println(coord1)
Update 2
There are some anti pattern in your code.
Class name should be in camel case
, like Cube so as ArrayList, LinkedList.
Why arrayList.display() need a argument which also reference to itself but you never use it (i.e. obj1 is totally ignored)?
coord1.display() is good enough, you don't need coord1.display(coord1)

You need to do following changes:
In your arrayList class you need to change methods display(Object obj1) and override toString() method:
public void display(Object obj1) {
System.out.println(obj1);
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < counter - 1; i++) {
sb.append(myList[i] + ",");
}
sb.append(myList[counter - 1] + "]");
return sb.toString();
}
In class linkedList change display and override toString() as below:
public void display() {
System.out.println(this.toString());
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
Cube temp = firstLink;
sb.append("[");
while (temp != null) {
sb.append(temp.obj.toString());
temp = temp.next;
if (temp != null)
sb.append(",");
}
sb.append("]");
return sb.toString();
}
}
Note: It will be printing linked list in reverse order, because your implementation of LinkedList is storing data in reverse order.

Related

Linked List is always null isEmpty() method I am trying to create is not working

public static void main (String[] args)
{
Student st1 = new Student("Adams", 3.6, 26);
Student st2 = new Student("Jones", 2.1, 29);
Student st3 = new Student("Marcus", 4.0, 53);
System.out.println("Testing non-recursive code");
LinkedListStud LL = new LinkedListStud();
//checks if linked list is empty
System.out.println("Linked list is empty?: " + LL.isEmpty());
//adds students to the linked list from the front
LL.addFront(st3);
LL.addFront(st2);
LL.addFront(st1);
//adds students to the linked list from the back
LL.addTail(st1);
LL.addTail(st2);
LL.addTail(st3);
//prints linked list non-recursively
LL.printLL();
System.out.println("Linked list is empty?: " + LL.isEmpty());
}
this is my testing method ^ as you can see I am filling my list with student objects. The printLL() method shows all 6 objects are in fact in the array.
public boolean isEmpty()
{
Boolean e;
if (list==null)
return e=true;
else
return e=false;
}
This is my isEmpty() method. The parameters and data type is specified by my professor. For some reason my list always equals null even though it should contain 6 objects the second time I use the method. What am I missing?
My entire linked list class
public class LinkedListStud
{
private Node list;
public LinkedListStud()
{
list = null;
}
public void addFront(Student s)
{
Node oneNode = new Node(s);
oneNode.next=list;
list=oneNode;
}
public void addTail(Student s)
{
Node current;
Node oneNode = new Node(s);
if (list==null)
list=oneNode;
else
{
current=list;
while (current.next != null)
current=current.next;
current.next=oneNode;
}
}
public boolean isEmpty()
{
Boolean e=true;
if (list!=null)
return false;
else
return e;
}
public Student bestStudent()
{
Student bestStudent=list.data;
while (list.next!=null)
{
if (list.next.data.getGpa()>list.data.getGpa())
{
Student temp = list.data;
list.data=list.next.data;
list.next.data=temp;
}
list=list.next;
}
return bestStudent;
}
public void printLL()
{
while (list!=null)
{
System.out.println(list.data);
list=list.next;
}
}
public void printLLRec(Node list)
{
if (list!=null)
{
System.out.println(list.data);
printLLRec(list.next);
}
}
Student bestStudRec(Node list)
{
Student bestStudent = list.data;
if (list!=null)
{
if (list.next.data.getGpa()>list.data.getGpa())
{
bestStudent=list.next.data;
bestStudRec(list.next);
}
}
return bestStudent;
}
private class Node
{
public Student data;
public Node next;
public Node(Student s)
{
data=s;
next=null;
}
public String toString()
{
return "" + data;
}
}
}
Problem is here:
public void printLL()
{
while (list!=null)
{
System.out.println(list.data);
list=list.next;
}
}
You replace list variable with nested list until it becomes null. Last iteration there set your LL.list to null, then while checks it and goes out. If you modify while like:
public void printLL()
{
while (list!=null)
{
System.out.println(list.data);
if (list.next == null) break;
list=list.next;
}
}
you will get what you need, but your root LL will have replaced value from last Node.
Following on from #Vadim 's answer, if you want to print it out without changing the internal list, you can introduce a local variable.
public void printLL()
{
Node temp = list;
while (temp!=null)
{
System.out.println(temp.data);
temp=temp.next;
}
}

Properly Writing Object Oriented Code in java for a stack

I'm trying to write code in a way that it is object oriented. In this particular case I want to keep track of the minimum value of my stack in O(1) time. I know how to do it, the idea of it, well my idea of it, which is to have another stack that keeps track of the minimum value for every push and pop.
I've nested every class inside of the program class which is called minStack, which doesn't seem like the right thing to do however when I create a instance of minStack and call its variables it works out fine for a regular stack. I created a class that extends a Stack called StackWithMin but I don't know how to call its values. Should I create a new instance of a StackWithMin? If so how would i do it? I did it at the end of the code above the main function, but peek() always returns null
class minStack {
public class Stack {
Node top;
Object min = null;
Object pop() {
if(top != null) {
Object item = top.getData();
top = top.getNext();
return item;
}
return null;
}
void push(Object item) {
if(min == null) {
min = item;
}
if((int)item < (int)min) {
min = item;
}
Node pushed = new Node(item, top);
top = pushed;
}
Object peek() {
if(top == null) {
//System.out.println("Its null or stack is empty");
return null;
}
return top.getData();
}
Object minimumValue() {
if(min == null) {
return null;
}
return (int)min;
}
}
public class Node {
Object data;
Node next;
public Node(Object data) {
this.data = data;
this.next = null;
}
public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
public void setNext(Node n) {
next = n;
}
public Node getNext() {
return next;
}
public void setData(Object d) {
data = d;
}
public Object getData() {
return data;
}
}
public class StackWithMin extends Stack {
Stack s2;
public StackWithMin() {
s2 = new Stack();
}
public void push(Object value) {
if((int)value <= (int)min()) {
s2.push(value);
}
super.push(value);
}
public Object pop() {
Object value = super.pop();
if((int)value == (int)min()) {
s2.pop();
}
return value;
}
public Object min() {
if(s2.top == null) {
return null;
}
else {
return s2.peek();
}
}
}
Stack testStack = new Stack();
StackWithMin stackMin = new StackWithMin();
public static void main(String[] args) {
minStack mStack = new minStack();
//StackWithMin stackMin = new StackWithMin();
mStack.testStack.push(3);
mStack.testStack.push(5);
mStack.testStack.push(2);
mStack.stackMin.push(2);
mStack.stackMin.push(4);
mStack.stackMin.push(1);
System.out.println(mStack.testStack.peek());
System.out.println(mStack.stackMin.peek());
mStack.testStack.pop();
}
}
I would suggest to create generic interface Stack like this one
interface Stack<T> {
void push(T item);
T pop();
T peek();
}
Generics add stability to your code by making more of your bugs
detectable at compile time.
See more about generics here.
Then implement this interface in a common way. All implementation details will be hidden inside of this class (your Node class for example). Here is the code (it is just to show the idea, if you want to use it you need to improve it with exception handling for example). Note that class Node is now also generic.
class SimpleStack<T> implements Stack<T> {
private class Node<T> { ... }
private Node<T> root = null;
public void push(T item) {
if (root == null) {
root = new Node<T>(item);
} else {
Node<T> node = new Node<T>(item, root);
root = node;
}
}
public T pop() {
if (root != null) {
T data = root.getData();
root = root.getNext();
return data;
} else {
return null;
}
}
public T peek() {
if (root != null) {
return root.getData();
} else {
return null;
}
}
}
Now we get to the part with stored minimum value. We can extend our SimpleStack class and add field with another SimpleStack. However I think this is better to make another implementation of the Stack and store two stacks for values and for minimums. The example is below. I have generalize the class that now uses Comparator to compare object, so you can use any other object types.
class StackWithComparator<T> implements Stack<T> {
private Comparator<T> comparator;
private SimpleStack<T> mins = new SimpleStack<>();
private SimpleStack<T> data = new SimpleStack<>();
public StackWithComparator(Comparator<T> comparator) {
this.comparator = comparator;
}
public void push(T item) {
data.push(item);
if (mins.peek() == null || comparator.compare(mins.peek(), item) >= 0) {
mins.push(item);
} else {
mins.push(mins.peek());
}
}
public T pop() {
mins.pop();
return data.pop();
}
public T peek() {
return data.peek();
}
public T min() {
return mins.peek();
}
}
Now you can use both implementations like so
SimpleStack<Integer> s1 = new SimpleStack<>();
s1.push(1);
s1.push(2);
s1.push(3);
System.out.println(s1.pop()); // print 3
System.out.println(s1.pop()); // print 2
System.out.println(s1.pop()); // print 1
StackWithComparator<Integer> s2 = new StackWithComparator<>(new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return Integer.compare(o1, o2);
}
});
s2.push(1);
s2.push(2);
s2.push(3);
s2.push(0);
s2.push(4);
System.out.println(s2.min() + " " + s2.pop()); // print 0 4
System.out.println(s2.min() + " " + s2.pop()); // print 0 0
System.out.println(s2.min() + " " + s2.pop()); // print 1 3
System.out.println(s2.min() + " " + s2.pop()); // print 1 2
System.out.println(s2.min() + " " + s2.pop()); // print 1 1

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.

JAVA: Simple pop does only return first item

I got following code set up:
public class ListStack implements Stack {
private class List {
List next;
Object object;
public List(Object o, List n) {
object = o;
next = n;
}
}
private List firstItem;
private int size;
public ListStack() {
firstItem = new List(null, null);
size = 0;
}
public List getEnd() {
List endEl = firstItem;
while (endEl.next != null) {
endEl = endEl.next;
}
return endEl;
}
public boolean push(Object o) {
List e1 = new List(o, null);
this.getEnd().next = e1;
size++;
return true;
}
public Object pop() {
if (this.firstItem.next == null) {
return null;
} else {
List endEl;
List tempEl;
endEl = this.getEnd();
tempEl = firstItem;
while (tempEl.next != endEl) {
tempEl = tempEl.next;
}
tempEl.next = null;
size--;
return tempEl.object;
}
}
public int size() {
return size;
}
public static void main(String[] args) {
Stack s = new ListStack();
Object test = new Object();
Object test2 = new Object();
System.out.println("pushing Object test to List: " + s.push(test));
System.out.println("pushing Object test2 to List: " + s.push(test2));
System.out.println("popping Object from List: " + s.pop());
System.out.println("popping Object from List: " + s.pop());
System.out.println("popping Object from List: " + s.pop());
}
}
And this one:
public interface Stack {
public int size();
public boolean push(Object o);
public Object pop();
}
But its only giving me the first object and twice "null" but it should give me the two objects :( where is my mistake? It is asking for the last item and gives it back (.object) but only returns first object adress
I think what your pop() function should return is endEl.object.
Your code is way too long-winded. A stack is a data structure that can efficiently push and pop elements. But your code has to traverse the whole stack for both operations (i. e. runs in O(n) instead of O(1) time.).
Prepending to your list is much more efficient as appending.
Example for an efficient push:
public void push(Object o) {
firstItem = new List(o, firstItem);
size++;
}

How to build a link list in Java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I implement a Linked List in Java?
We know there is no pointers in java. Then what is the best way to build the link list in java?
The best way is to not build it. Java already has a LinkedList class amongst its rather large selection of collection classes.
You would be better off using what the language/library already provides.
You have an object that essentially contains two variables, no methods (bare minimum; however, you could have methods if you wanted). Something like:
class Link
{
int data;
Link next;
}
Then you create a new Link like any other object. Set the data to the data you want a node to hold. Then set the Link node to the node that it will be "pointing" to (or null if it doesn't point to another one).
Note: you can also have a previous node (which points to the previous node) if need be.
try having this code.
public class Main {
public static void main(String[] args) {
LinkedList theList = new LinkedList();
LinkedListIterator theItr;
theItr = theList.zeroth();
printList(theList);
for (int i = 0; i < 10; i++) {
theList.insert(new Integer(i), theItr);
printList(theList);
theItr.advance();
}
System.out.println("Size was: " + listSize(theList));
}
public static int listSize(LinkedList theList) {
LinkedListIterator itr;
int size = 0;
for (itr = theList.first(); itr.isValid(); itr.advance())
size++;
return size;
}
public static void printList(LinkedList theList) {
if (theList.isEmpty())
System.out.print("Empty list");
else {
LinkedListIterator itr = theList.first();
for (; itr.isValid(); itr.advance())
System.out.print(itr.retrieve() + " ");
}
System.out.println();
}
}
class LinkedList {
public LinkedList() {
header = new ListNode(null);
}
public boolean isEmpty() {
return header.next == null;
}
public void makeEmpty() {
header.next = null;
}
public LinkedListIterator zeroth() {
return new LinkedListIterator(header);
}
public LinkedListIterator first() {
return new LinkedListIterator(header.next);
}
public void insert(Object x, LinkedListIterator p) {
if (p != null && p.current != null)
p.current.next = new ListNode(x, p.current.next);
}
public LinkedListIterator find(Object x) {
ListNode itr = header.next;
while (itr != null && !itr.element.equals(x))
itr = itr.next;
return new LinkedListIterator(itr);
}
public LinkedListIterator findPrevious(Object x) {
ListNode itr = header;
while (itr.next != null && !itr.next.element.equals(x))
itr = itr.next;
return new LinkedListIterator(itr);
}
public void remove(Object x) {
LinkedListIterator p = findPrevious(x);
if (p.current.next != null)
p.current.next = p.current.next.next; // Bypass deleted node
}
private ListNode header;
}
class LinkedListIterator {
LinkedListIterator(ListNode theNode) {
current = theNode;
}
public boolean isValid() {
return current != null;
}
public Object retrieve() {
return isValid() ? current.element : null;
}
public void advance() {
if (isValid())
current = current.next;
}
ListNode current;
}
class ListNode {
public ListNode(Object theElement) {
this(theElement, null);
}
public ListNode(Object theElement, ListNode n) {
element = theElement;
next = n;
}
public Object element;
public ListNode next;
}

Categories