How to fill getItemSize() method in my java code - java

I have a DListNode class with a member name item.
/* DListNode.java */
/**
* DListNode is a node in DList(Doubly linked list).
* #author mohet01
*
*/
public class DListNode {
/**
* item references the item stored in the current node.
* prev references the previous node in the DList.
* next references the next node in the DList.
*/
Object item;
DListNode prev;
DListNode next;
/**
* DListNode constructor with zero args
*/
public DListNode(){
this.item=null;
this.prev=null;
this.next=null;
}
/**
* DListNode constructor with one arg
*/
public DListNode(Object obj){
this.item = obj;
this.prev = null;
this.next = null;
}
/**
* getItem() returns the size of the queried item
* #return
*/
public Object getItemSize() {
//solution required
return item;
}
}
If DListNode member item points to object of type TypeAndSize class,
public class TypeAndSize {
public int type; //Ocean.EMPTY, Ocean.UNVISITEDSHARK, or Ocean.FISH
public int size; // Number of cells in the run
/**
* Constructor for a TypeAndSize of specified species and run length.
* #param species is Ocean.EMPTY, Ocean.SHARK, or Ocean.FISH.
* #param runLength is the number of identical cells in this run.
* #return the newly constructed Critter.
*
*/
public TypeAndSize(int species, int runLength){
if((species != Ocean.EMPTY) && (species != Ocean.SHARK) && (species != Ocean.FISH)){
System.out.println("TypeAndSize Error: Illegal species.");
System.exit(1);
}
if(runLength < 1){
System.out.println("TypeAndSize Error: runLength must be atleast 1.");
System.exit(1);
}
this.type = species;
this.size = runLength;
}
public int getSize(){
return size;
}
}
My goal is to bring the member size by writing code in getItemSize() method of DListNode class.
These above two classes are skeletons given by professor.
http://www.cs.berkeley.edu/~jrs/61bf06/hw/pj1/
I created getSize() method in TypeAndSize class.
Please help me!!!
FYI...
This is my first experience in using such scenario, as am learning java at home from cs61B Fall 2006 Berkeley course webcast. This is part of assignment in Project1
Please help me!!!

Assuming you will call this method only on the first of the elements of the list, this should solve your problem:
public int getItemSize() {
int size = 0;
DListNode node = this;
while (node != null) {
size++;
node = node.next;
}
return size;
}
If you want this to be called from any node, use this other solution
public Object getItemSize() {
int size = 0;
DListNode node = this;
while (node != null) {
size++;
node = node.next;
}
node = prev;
while (node != null) {
size++;
node = node.prev;
}
return size;
}

Related

Why does my toString() method not return my Singly Linked List in a string format?

I am trying to implement a toString() method that returns the values in my singly-linked list in a string format by iterating through the list. See below for the SinglyLinkedList.java file which contains the toString() method.
import java.util.NoSuchElementException;
import java.util.*;
/**
* Your implementation of a Singly-Linked List.
*/
public class SinglyLinkedList<T> {
/*
* Do not add new instance variables or modify existing ones.
*/
private SinglyLinkedListNode<T> head;
private SinglyLinkedListNode<T> tail;
private int size;
/*
* Do not add a constructor.
*/
/**
* Adds the element to the front of the list.
*
* Method should run in O(1) time.
*
* #param data the data to add to the front of the list
* #throws java.lang.IllegalArgumentException if data is null
*/
public void addToFront(T data) {
if (data == null){
throw new IllegalArgumentException("Data cannot be null");
}
SinglyLinkedListNode<T> newNode = new SinglyLinkedListNode<T>(data);
if (head == null){
head = newNode;
tail = newNode;
}
else{
newNode.setNext(head);
head = newNode;
}
size++;
}
/**
* Adds the element to the back of the list.
*
* Method should run in O(1) time.
*
* #param data the data to add to the back of the list
* #throws java.lang.IllegalArgumentException if data is null
*/
public void addToBack(T data) {
if (data == null){
throw new IllegalArgumentException("Data cannot be null");
}
if (head == null){
head = new SinglyLinkedListNode<T>(data);
}
else {
SinglyLinkedListNode<T> current = head;
while (current.getNext() != null){
current = current.getNext();
}
current.setNext(new SinglyLinkedListNode<T>(data));
}
size++;
}
/**
* Removes and returns the first data of the list.
*
* Method should run in O(1) time.
*
* #return the data formerly located at the front of the list
* #throws java.util.NoSuchElementException if the list is empty
*/
public T removeFromFront() {
if (head == null){
throw new NoSuchElementException("You cannot remove elements from the front of an empty list");
}
SinglyLinkedListNode<T> var = head;
head = head.getNext();
size--;
return var.getData();
}
/**
* Removes and returns the last data of the list.
*
* Method should run in O(n) time.
*
* #return the data formerly located at the back of the list
* #throws java.util.NoSuchElementException if the list is empty
*/
public T removeFromBack() {
if (head == null){
throw new NoSuchElementException("You cannot remove an element from the back of an empty list");
}
else if (head.getNext() == null){
SinglyLinkedListNode<T> var = head;
head = null;
}
SinglyLinkedListNode<T> current = head;
while (current.getNext().getNext() != null){
current = current.getNext();
}
SinglyLinkedListNode<T> var = current.getNext();
current.setNext(null);
size--;
return var.getData();
}
/**
* Returns the head node of the list.
*
* For grading purposes only. You shouldn't need to use this method since
* you have direct access to the variable.
*
* #return the node at the head of the list
*/
public SinglyLinkedListNode<T> getHead() {
// DO NOT MODIFY THIS METHOD!
return head;
}
/**
* Returns the tail node of the list.
*
* For grading purposes only. You shouldn't need to use this method since
* you have direct access to the variable.
*
* #return the node at the tail of the list
*/
public SinglyLinkedListNode<T> getTail() {
// DO NOT MODIFY THIS METHOD!
return tail;
}
/**
* Returns the size of the list.
*
* For grading purposes only. You shouldn't need to use this method since
* you have direct access to the variable.
*
* #return the size of the list
*/
public int size() {
// DO NOT MODIFY THIS METHOD!
return size;
}
public String toString() {
String answer = "";
SinglyLinkedListNode<T> current = head;
while (current != null){
answer += current + " ";
current = current.getNext();
}
return answer;
}
public static void main(String[] args){
SinglyLinkedList<Integer> list = new SinglyLinkedList<>();
list.addToFront(1);
System.out.println(list.toString());
}
}
And for my SinglyLinkedListNode.java file...
/**
* Node class used for implementing the SinglyLinkedList.
*
* DO NOT MODIFY THIS FILE!!
*
* #author CS 1332 TAs
* #version 1.0
*/
public class SinglyLinkedListNode<T> {
private T data;
private SinglyLinkedListNode<T> next;
/**
* Constructs a new SinglyLinkedListNode with the given data and next node
* reference.
*
* #param data the data stored in the new node
* #param next the next node in the list
*/
SinglyLinkedListNode(T data, SinglyLinkedListNode<T> next) {
this.data = data;
this.next = next;
}
/**
* Creates a new SinglyLinkedListNode with only the given data.
*
* #param data the data stored in the new node
*/
SinglyLinkedListNode(T data) {
this(data, null);
}
/**
* Gets the data.
*
* #return the data
*/
T getData() {
return data;
}
/**
* Gets the next node.
*
* #return the next node
*/
SinglyLinkedListNode<T> getNext() {
return next;
}
/**
* Sets the next node.
*
* #param next the new next node
*/
void setNext(SinglyLinkedListNode<T> next) {
this.next = next;
}
}
Whenever I call the toString() method from my SinglyLinkedList class, I get the following printed in my command prompt.
Command Prompt
Does anyone know why I do not see the value "1" which I am adding to the front of the linkedlist prior to calling the toString() method? And if so, what can I do to fix it? Instead, it keeps printing the node object.
The problem is you have an object 'current' of type SinglyLinkedList whose toString method is not overridden.
public String toString() {
String answer = "";
SinglyLinkedListNode<T> current = head;
while (current != null){
answer += current + " ";
current = current.getNext();
}
return answer;
}
If you cannot override toString method in SinglyLinkedListNode class then you can modify the while loop to:
while(current != null){
answer += current.getData() + " ";
current = current.getNext();
}
Assuming your T has appropriate toString() method overridden.
To make the code more efficient you can use StringBuilder rather than concatenating strings.
public String toString() {
//String answer = " ";
StringBuilder answer = new StringBuilder();
SinglyLinkedListNode<T> current = head;
while (current != null){
//answer += current + " ";
answer.append(current.getData());
answer.append(" ");
current = current.getNext();
}
return answer.toString();
}

Instantiate each element of an ArrayList of type LinkedQueue as a letter of the alphabet

I want to instantiate each element of my ArrayList of type LinkedQueue (size 26, one queue for each letter of the alphabet). Off the top of my head -- because I haven't worked with LinkedQueues very much, I wrote this:
public void initializeList() {
ArrayList<LinkedQueue> arrayList = new ArrayList<LinkedQueue>();
String letters = "abcdefghijklmnopqrstuvwxyz";
for(int i = 0; i < letters.length(); i++){
arrayList.add(letters.charAt(i));
}
}
But I get an error that says: "The method add(LinkedQueue) in the type ArrayList is not applicable for the arguments (char)." I still haven't completely mastered Java; could someone help me understand what this means and what I'm doing wrong (or possible recommend a better solution)?
For reference, this is the LinkedQueue class:
public class LinkedQueue<T> implements QueueADT<T>
{
private int count;
private LinearNode<T> head, tail;
/**
* Creates an empty queue.
*/
public LinkedQueue()
{
count = 0;
head = tail = null;
}
/**
* Adds the specified element to the tail of this queue.
* #param element the element to be added to the tail of the queue
*/
public void enqueue(T element)
{
LinearNode<T> node = new LinearNode<T>(element);
if (isEmpty())
head = node;
else
tail.setNext(node);
tail = node;
count++;
}
/**
* Removes the element at the head of this queue and returns a
* reference to it.
* #return the element at the head of this queue
* #throws EmptyCollectionException if the queue is empty
*/
public T dequeue() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("queue");
T result = head.getElement();
head = head.getNext();
count--;
if (isEmpty())
tail = null;
return result;
}
/**
* Returns a reference to the element at the head of this queue.
* The element is not removed from the queue.
* #return a reference to the first element in this queue
* #throws EmptyCollectionsException if the queue is empty
*/
public T first() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("Queue is empty");
return head.getElement();
}
/**
* Returns true if this queue is empty and false otherwise.
* #return true if this queue is empty
*/
public boolean isEmpty()
{
return count==0;
}
/**
* Returns the number of elements currently in this queue.
* #return the number of elements in the queue
*/
public int size()
{
return count;
}
/**
* Returns a string representation of this queue.
* #return the string representation of the queue
*/
public String toString()
{
StringBuilder s = new StringBuilder("");
LinearNode<T> current = head;
while (current != null) {
s.append(current.getElement());
s.append("\n");
current = current.getNext();
}
return s.toString();
}
/**
* Returns true if the list in the parameter has the same length and data elements
* as "this" Linked Queue. Returns false otherwise.
* #return true if the lists are equal
*/
#Override
public boolean equals(LinkedQueue<T> list) {
// Lab exercise 1. Fill in this method.
return true;
}
/**
* Returns a LinkedQueue that contains the same data elements as "this", but in
* reverse order
* #return a LinkedQueue that is the reverse of this queue
*/
public LinkedQueue<T> reverse() {
// Lab exercise 2. Fill in this method.
return null;
}
}

print() function that prints the contents of each element of your list

Basically i'm trying to write a print statement that will allow me to print the elements per line as a println as the output when i run the driver.java. And for the life of me i cannot figure out how to do it. Any help will be appreciated.
here is the driver.java
public class Driver {
public static void main(String args[]){
LList<String> s_list = new LList<String>();
s_list.insert("New York, 8.4M");
s_list.insert("Los Angeles 3.8M");
s_list.insert("Chicago, 2.7M");
s_list.insert("Houston, 2.1M");
s_list.insert("Philadelphia, 1.55M");
s_list.insert("Phoenix, 1.51M");
s_list.append("San Antonio, 1.4M");
s_list.append("San Diego, 1.35M");
s_list.append("Dallas, 1.25M");
s_list.append("San Jose, 0.998M");
s_list.append("Austin, 0.88M");
s_list.append("Indianapolis, 0.84M");
s_list.append("Jacksonville, 0.84M");
s_list.append("San Francisco, 0.83M");
s_list.append("Columbus, 0.82M");
s_list.append("Charlotte, 0.79M");
s_list.print();
s_list.moveToPos(3);
s_list.remove();
s_list.print();
s_list.moveToEnd();
s_list.remove();
s_list.print();
s_list.moveToStart();
s_list.remove();
s_list.remove();
s_list.print();
s_list.clear();
s_list.print();
}
}
and I have a java file named LList.java
where I am trying to write a print method where it will print() function that prints the contents of each element of your list; print one element per line.
public void print {
}
So, How will i print the elements in "s_list" line per line as output.
Any help is appreciated.
UPDATE: I am going to post Llist.java,list.java & link.java here
Llist.java
/** Linked list implementation */
class LList<E> implements List<E> {
private Link<E> head; // Pointer to list header
private Link<E> tail; // Pointer to last element
protected Link<E> curr; // Access to current element
private int cnt; // Size of list
/** Constructors */
LList(int size) { this(); } // Constructor -- Ignore size
LList() {
curr = tail = head = new Link<E>(null); // Create header
cnt = 0;
}
/** Remove all elements */
public void clear() {
head.setNext(null); // Drop access to links
curr = tail = head = new Link<E>(null); // Create header
cnt = 0;
}
/** Insert "it" at current position */
public void insert(E it) {
curr.setNext(new Link<E>(it, curr.next()));
if (tail == curr) tail = curr.next(); // New tail
cnt++;
}
/** Append "it" to list */
public void append(E it) {
tail = tail.setNext(new Link<E>(it, null));
cnt++;
}
/** Remove and return current element */
public E remove() {
if (curr.next() == null) return null; // Nothing to remove
E it = curr.next().element(); // Remember value
if (tail == curr.next()) tail = curr; // Removed last
curr.setNext(curr.next().next()); // Remove from list
cnt--; // Decrement count
return it; // Return value
}
/** Set curr at list start */
public void moveToStart()
{ curr = head; }
/** Set curr at list end */
public void moveToEnd()
{ curr = tail; }
/** Move curr one step left; no change if now at front */
public void prev() {
if (curr == head) return; // No previous element
Link<E> temp = head;
// March down list until we find the previous element
while (temp.next() != curr) temp = temp.next();
curr = temp;
}
/** Move curr one step right; no change if now at end */
public void next()
{ if (curr != tail) curr = curr.next(); }
/** #return List length */
public int length() { return cnt; }
/** #return The position of the current element */
public int currPos() {
Link<E> temp = head;
int i;
for (i=0; curr != temp; i++)
temp = temp.next();
return i;
}
/** Move down list to "pos" position */
public void moveToPos(int pos) {
assert (pos>=0) && (pos<=cnt) : "Position out of range";
curr = head;
for(int i=0; i<pos; i++) curr = curr.next();
}
/** #return Current element value */
public E getValue() {
if(curr.next() == null) return null;
return curr.next().element();
}
public void print()
{
}
}
List.java
/** List ADT */
public interface List<E> {
/** Remove all contents from the list, so it is once again
empty. Client is responsible for reclaiming storage
used by the list elements. */
public void clear();
/** Insert an element at the current location. The client
must ensure that the list�s capacity is not exceeded.
#param item The element to be inserted. */
public void insert(E item);
/** Append an element at the end of the list. The client
must ensure that the list�s capacity is not exceeded.
#param item The element to be appended. */
public void append(E item);
/** Remove and return the current element.
#return The element that was removed. */
public E remove();
/** Set the current position to the start of the list */
public void moveToStart();
/** Set the current position to the end of the list */
public void moveToEnd();
/** Move the current position one step left. No change
if already at beginning. */
public void prev();
/** Move the current position one step right. No change
if already at end. */
public void next();
/** #return The number of elements in the list. */
public int length();
/** #return The position of the current element. */
public int currPos();
/** Set current position.
#param pos The position to make current. */
public void moveToPos(int pos);
/** #return The current element. */
public E getValue();
}
Link.java
/** Singly linked list node */
class Link<E> {
private E element; // Value for this node
private Link<E> next; // Pointer to next node in list
// Constructors
Link(E it, Link<E> nextval)
{ element = it; next = nextval; }
Link(Link<E> nextval) { next = nextval; }
Link<E> next() { return next; } // Return next field
Link<E> setNext(Link<E> nextval) // Set next field
{ return next = nextval; } // Return element field
E element() { return element; } // Set element field
E setElement(E it) { return element = it; }
}
We will need to see inside the class of LList.java... but for now i am going to assume LList extends List [or ArrayList, etc..]
public void print
{
for(int i = 0; i < this.size(); i++) //this really depends on how you store your list
System.out.println(this.get(i));
}
This all depends on how your LList.java looks though... [this.size()] refers to the List or ArrayList class [if you extended it...].
If you are not extending List or something along those lines, you could always do:
public void print
{
for(int i = 0; i < storingArray.size(); /*or .length*/ i++)
System.out.println(storingArray.get(i)); /*or storingArray[i]*/
}
But as always, you could take the easy way and just do:
list.foreach(System.out::println); //must have Java 8.
Revised Answer based on your comments:
public void print() {
Link<E> currentNode = head; //Sets starting node to first node in list
while (currentNode != tail) { //Checks if current node is equal to last node
System.out.println(currentNode.element()); //Prints currentNodes's element
currentNode = currentNode.next(); //Sets currentNode to next node in list
}
System.out.println(tail.element()); //Prints last node in list
}
Note: Some of your comments in you Link<E>code don't match what your functions are actually doing.

A* Algorithm Java

I have spent entire weekend playing around with this. I am trying to store the nodes in PriorityQueue data structure. My astar function doesnt seem to be doing what it should. Anyone mind having a look?
public void aStar(Node from, Node to) {
PriorityQueue<Node> exploreList = new PriorityQueue<Node>();
ArrayList<Node> visited = new ArrayList<Node>();
ArrayList<Node> successors = new ArrayList<Node>();
Node current = from;
System.out.println(current.getName());
while (current != to) {
successors = current.getConnected();
Collections.sort(successors);
for (Node n : successors) {
if (!visited.contains(n)) {
exploreList.add(n);
}
for (Node n1 : successors) {
if (n.fSum() > n1.fSum()) {
exploreList.remove(n);
exploreList.add(n1);
}
}
}
visited.add(current);
current = exploreList.remove();
System.out.println(current.getName());
}
Node Class here
public class Node implements Comparable {
private String name;
private int travDist;
private int straightDist;
private ArrayList<Arc> arcs;
/**
* Constructor for a new node
*
* #param n
*/
public Node(String n, int aTravDist, int aStraightDist) {
name = n;
travDist = aTravDist;
straightDist = aStraightDist;
arcs = new ArrayList<Arc>();
}
/**
* Adds a new arc
*
* #param to
* #param c
*/
public void addArc(Node to, int c) {
arcs.add(new Arc(to, c));
}
/**
* Gets the list of connected nodes to this node
*
* #return
*/
public ArrayList<Node> getConnected() {
ArrayList<Node> returnData = new ArrayList<Node>();
for (Arc a : arcs) {
returnData.add(a.getNode());
}
return returnData;
}
#Override
public int compareTo(Object o) {
//return name.compareTo(((Node) o).getName());
Integer sum = ((Node)o).fSum();
return sum.compareTo(fSum());
}
public int fSum () {
return travDist + straightDist;
}
/**
* Gets the name of the Node
*
* #return
*/
public String getName() {
return name;
}
}
What you are doing is not a proper A star algorithm.
Collections.sort(successors);
You shouldn't do that. In A star you always consider all the successors. You needn't worry about the order- the priority queue will take care of that. However, adding this line increases the complexity of the algorithm.
for (Node n1 : successors) {
if (n.fSum() > n1.fSum()) {
exploreList.remove(n);
exploreList.add(n1);
}
}
This is entirely wrong. What you are doing here is: you only add the closest of all the successors. This will be a beam search with a beam of size 1, not A star - just keep them all in.

Implementing a Linked List Stack and Queue, and I don't know if the code I have set up is efficient enough

Been working on an implementation for Linked list Queue and Stack classes for an assignment. I've tested both of these and they appear to be working, but I'm worried that some parts of the implementation can be done better than I currently have set up, and I don't wanna get points taken off for inefficient code.
Here's the classes I have set up:
Node
public class Node {
Node next;
Car car;
/**
* A node object, used for the creation of LinkedLists.
* #param car
*/
public Node(Car car)
{
next = null;
this.car = car;
}
}
Stack
public class LStack {
Node head = null;
/**
* Adds a car object to the list
* #param car = the car object to be added
*/
public void push(Car car)
{
Node oldHead = head;
head = new Node(car);
head.next = oldHead;
}
/**
* Removes the top car from the list
* #return the car at the top of the list
*/
public Car pop()
{
Car headCar = head.car;
head = head.next;
return headCar;
}
/**
* Checks if the list is empty
* #return whether or not the list is empty
*/
public boolean isEmpty()
{
return (head == null);
}
/**
*
* #return the size of the list
*/
public int size()
{
Node nextNode = head;
int count = 0;
while (nextNode != null)
{
count++;
nextNode = nextNode.next;
}
return count;
}
/**
* Displays the list of car license plate information
*/
public void display()
{
Node nextNode = head;
while (nextNode != null)
{
System.out.print(nextNode.car.getLicense() + "|");
nextNode = nextNode.next;
}
System.out.println();
}
/**
*
*/
public void reverseStack()
{
// not implemented yet
}
}
Queue
public class LQueue {
Node head = null;
/**
* Adds a car object to the list
*
* #param car
* = the car object to be added
*/
public void insert(Car car) {
Node current = head;
if (current != null) {
while (current.next != null) {
current = current.next;
}
current.next = new Node(car);
}
else
{
head = new Node(car);
}
}
/**
* Removes the top car from the list
*
* #return the car at the top of the list
*/
public Car remove() {
Car headCar = head.car;
head = head.next;
return headCar;
}
/**
* Checks if the list is empty
*
* #return whether or not the list is empty
*/
public boolean isEmpty() {
return (head == null);
}
/**
*
* #return the size of the list
*/
public int size() {
Node nextNode = head;
int count = 0;
while (nextNode != null) {
count++;
nextNode = nextNode.next;
}
return count;
}
/**
* Displays the list of car license plate information
*/
public void display() {
Node nextNode = head;
while (nextNode != null) {
System.out.print(nextNode.car.getLicense() + "|");
nextNode = nextNode.next;
}
System.out.println();
}
/**
*
*/
public void reverseQueue() {
}
}
and the Car class isn't really important, it just stores license plate information in a string.
Mostly I'm worried about the ones I have set up with the While loops, I'm not sure if there's a more memory efficient way of implementing those. Is there a more standardized way of setting these up that I may have missed?
One thing that I would change is that I'd make LQueue keep references to both the head and the tail of the queue. This way you'd be able to insert() in constant time, without having to iterate over all existing elements.
Also, both size() methods can be made to run in constant time if you so wished: keep track of the current size in a member variable, increment on insert() and decrement on remove().
The only two things I can think of are:
Keep track of the number of elements in the list with an int that increments on add and decrements on remove. This would make the size() method instant. All you would have to do is return that int value.
For the queue, keep track of the tail with a Node reference much like you do the head. That way you don't have to iterate through the list to find the end of the list. The tail would just always be the last added Node. This would allow you to not have to iterate through the list every time you want to add something; instead you could just add it to the end of that tail.

Categories

Resources