How can I hold the max of a stack? - java

Been banging my head against a wall for a week and cannot seem to get anywhere. I want to be able to get the max from the stack and keep it in the stack so in the end there is a only one value in the Stack and that is the max. I believe my algorithm to keep the max is correct, but I think my pop method is malfunctioning and I cannot figure out why. Any guidance is appreciated. Both files I am working with are included
import java.io.File;
import java.io.IOException;
import java.util.ListIterator;
import java.util.Random;
public class LinkedListStack {
DoublyLinkedList<Integer> list = new DoublyLinkedList<Integer>();
public int size() {
if (list.isEmpty()) {
System.out.println("Stack is empty");
}
return list.size();
}
public void push(Integer s) {
list.add(s);
}
public Integer pop() {
/* need help with this method */
}
public Integer top() {
return list.iterator().next();
}
public boolean isEmpty() {
return list.isEmpty();
}
public String displayStack() {
return (list.toString());
}
public static void main(String[] args) throws IOException {
LinkedListStack stack = new LinkedListStack();
int n, seed;
File outputFile;
File dir = new File(".");
if (args.length > 0) {
n = Integer.parseInt(args[0]);
seed = Integer.parseInt(args[1]);
}else {
n = 10;
seed = 1;
}
if (args.length == 3) {
outputFile = new File(args[2]);
} else {
outputFile = new File(dir.getCanonicalPath() + File.separator + "Files/testOut_Stack");
}
OutputWriter out = new OutputWriter(outputFile);
Random r = new Random(seed);
Integer nextval;
for (int i = 0; i < n; i++) {
nextval = r.nextInt(10000);
if (stack.isEmpty()) {
stack.push(nextval);
}
if (nextval > stack.top()) {
stack.pop();
stack.push(nextval);
}
/* retain the max value that you see among the integers generated in the stack.
* In the end there should be only one integer in stack, which is the max value
*/
}
// write the content of stack -- which is the max value -- to file
out.writeOutput(stack.displayStack());
}
}
import java.io.File;
import java.io.IOException;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Random;
import csci3230.hw3.OutputWriter;
public class DoublyLinkedList<Item> implements Iterable<Item> {
private int n; // number of elements on list
private Node pre; // sentinel before first item
private Node post; // sentinel after last item
public DoublyLinkedList() {
pre = new Node();
post = new Node();
pre.next = post;
post.prev = pre;
}
// linked list node helper data type
private class Node {
private Item item;
private Node next;
private Node prev;
}
public boolean isEmpty() {
return (n == 0);
// your code
}
public int size() {
return n;
// your code
}
// add the item to the list
public void add(Item item) {
Node last = post.prev;
Node x = new Node();
x.item = item;
x.next = post;
x.prev = last;
post.prev = x;
last.next = x;
n++;
// your code
}
public ListIterator<Item> iterator() { return new DoublyLinkedListIterator(); }
// assumes no calls to DoublyLinkedList.add() during iteration
private class DoublyLinkedListIterator implements ListIterator<Item> {
private Node current = pre.next; // the node that is returned by next()
private Node lastAccessed = null; // the last node to be returned by prev() or next()
// reset to null upon intervening remove() or add()
private int index = 0;
public boolean hasNext() {
return (index < n); // your code
}
public boolean hasPrevious() {
return (index > 0);
// your code
}
public int previousIndex() {
return (index - 1);
// your code
}
public int nextIndex() {
return (index + 1);
// your code
}
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
lastAccessed = current;
Item item = current.item;
current = current.next;
index++;
return item;
// your code
}
public Item previous() {
if (!hasPrevious()) throw new NoSuchElementException();
current = current.prev;
index--;
lastAccessed = current;
return current.item;
// your code
}
// replace the item of the element that was last accessed by next() or previous()
// condition: no calls to remove() or add() after last call to next() or previous()
public void set(Item item) {
if (lastAccessed == null) throw new IllegalStateException();
lastAccessed.item = item;
// your code
}
// remove the element that was last accessed by next() or previous()
// condition: no calls to remove() or add() after last call to next() or previous()
public void remove() {
if (lastAccessed == null) throw new IllegalStateException();
Node x = lastAccessed.prev;
Node y = lastAccessed.next;
x.next = y;
y .prev = x;
n--;
if (current == lastAccessed) {
current = y;
}
else {
index--;
}
lastAccessed = null;
// your code
}
// add element to list
public void add(Item item) {
Node x = current.prev;
Node y = new Node();
Node z = current;
y.item = item;
x.next = y;
y.next = z;
z.prev = y;
y.prev = x;
n++;
index++;
lastAccessed = null;
// your code
}
}
public String toString() {
StringBuilder s = new StringBuilder();
for (Item item : this)
s.append(item + " ");
return s.toString();
}
}

You can keep the first integer you pop as a temporary "largestValue" and compare every subsequent integer you pop with it to see whether you should replace it. At the very of your function, pop all values and add the largestValue back onto it.

Related

How to speed up Depth First Search method?

I'm trying to do a Depth First Search of my graph, and something is slowing it down quite a lot and I'm not sure what.
Here is my Bag code:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Bag<Item> implements Iterable<Item> {
private Node<Item> first; // beginning of bag
private Node<Item> end;
private int n; // number of elements in bag
public int label;
public int edges;
public static class Node<Item> {
private Item item;
private Node<Item> next;
public int label;
public int edges;
}
public Bag() {
first = null; // empty bag initialized
end = null;
n = 0;
}
public void add(Item item) {
if (n==0) {
Node<Item> head = new Node<Item>(); // if bag is empty
first = head;
end = head;
head.item = item; // new node both first and end of bag
edges++;
n++;
}
else {
Node<Item> oldlast = end; // old last assigned to end of node
Node<Item> last = new Node<Item>();
last.item = item;
oldlast.next = last; // new node added after old last
end = last;
n++; // size increased
edges++;
}
}
public Iterator<Item> iterator() {
return new LinkedIterator(first); // returns an iterator that iterates over the items in this bag in arbitrary order
}
public class LinkedIterator implements Iterator<Item> {
private Node<Item> current;
public LinkedIterator(Node<Item> first) {
current = first; // iterator starts at head of bag
}
public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); }
public Item next() {
if (!hasNext()) throw new NoSuchElementException(); // if there is next item, current is moved to next
Item item = current.item;
current = current.next;
return item; // item is returned
}
}
}
Here is my driver:
import java.util.ArrayList;
import java.util.Random;
public class Driver {
public static ArrayList<Integer> randomNum(int howMany) {
ArrayList<Integer> numbers = new ArrayList<Integer>(howMany);
Random randomGenerator = new Random();
while (numbers.size() < howMany) {
int rand_int = randomGenerator.nextInt(10000);
if (!numbers.contains(rand_int)) {
numbers.add(rand_int);
}
}
return numbers;
}
public static void main(String[] args) {
ArrayList<Integer> num = randomNum(100);
Graph G = new Graph(num);
System.out.println("The length of longest path for this sequence with graph is: " + G.dfsStart(num));
}
}
I send an ArrayList of random integers to my dfsStart method from the driver, which looks at all the different paths for each starting node in my graph. my DepthFirstSearch method calls the getAdjList for each starting node to find its neighbors using my Bag adj, and then works its way down each path before backtracking.
Here is my Graph code, containing my longest path method:
import java.util.ArrayList;
import java.util.NoSuchElementException;
public class Graph {
public final int V; // initializing variables and data structures
public Bag<Integer>[] adj;
public int longestPath;
public Graph(ArrayList<Integer> numbers) {
try {
longestPath = 0;
this.V = numbers.size();
adj = (Bag<Integer>[]) new Bag[V]; // bag initialized
for (int v = 0; v < V; v++) {
adj[v] = new Bag<Integer>();
}
for (int i = 0; i < V; i++) {
adj[i].label = numbers.get(i);
int j = (i + 1);
while (j < numbers.size()) {
if (numbers.get(i) < numbers.get(j)) {
addEdge(i, numbers.get(j));
}
j++;
}
}
}
catch (NoSuchElementException e) {
throw new IllegalArgumentException("invalid input format in Graph constructor", e);
}
}
public void addEdge(int index, int num) {
adj[index].add(num);
}
public int getIndex(int num) {
for (int i = 0; i < adj.length; i++) {
if (adj[i].label == num) {
return i;
}
}
return -1;
}
public Bag<Integer> getAdjList(int source) {
Bag<Integer> adjList = null;
for (Bag<Integer> list : adj) {
if (list.label == source) {
adjList = list;
break;
}
}
return adjList;
}
public int dfsStart(ArrayList<Integer> numbers) {
for (int i=0;i<numbers.size();i++) {
// Print all paths from current node
depthFirstSearch(numbers.get(i),new ArrayList<>(300));
}
return longestPath;
}
public void depthFirstSearch(int src, ArrayList<Integer> current) {
current.add(src);
Bag<Integer> srcAdj = getAdjList(src);
if (srcAdj.size() == 0) {
// Leaf node
// Print this path
longestPath = Math.max(longestPath, current.size());
}
for (int links : srcAdj) {
depthFirstSearch(links, current);
}
current.remove(current.size()-1);
}
}
I believe the suggestion below helped get rid of the error, but it is still unbelievably slow when trying to find the longest path in a graph of more than 150 vertices.
Even for a small dense graph there can be many unique paths from a src node. I tested for this input [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25] there are 16777216 unique paths from all nodes. So you can expect OOM for bigger inputs. one way is to update the longestPath as soon as a path is found instead of adding it to the list.
Change this to later.
addtoCount(current.size());
to
longestPath = Math.max(longestPath, current.size());
Make sure longestPath is global and initialized to 0 before every test case.
Well, I do not know JAVA but that is an incredible lot of code for doing a simple thing such as depth first search.
In C++ it is done like this:
void cPathFinder::depthFirst(
int v)
{
// initialize visited flag for each node in graph
myPath.clear();
myPath.resize(nodeCount(), 0);
// start recursive search from starting node
depthRecurse(v, visitor);
}
void cPathFinder::depthRecurse(
int v )
{
// remember this node has been visited
myPath[v] = 1;
// look for new adjacent nodes
for (int w : adjacent(v))
if (!myPath[w])
{
// search from new node
depthRecurse(w);
}
}

How To Implement Correct Sorting Algorithm in Priority Queue?

I need your help with implementing the correct sorting algorithm for Priority Queue. Apparently I've done this wrong as it creates a duplicate node. I'm stumped on this, any help would be greatly appreciated. I need to get this right as I will use this on both increase() and decrease() methods.
Check my sort() method below in the code.
Here is my code:
public class PriorityQueueIntegers implements PriorityQueueInterface {
// number of elements
private int numberOfElements;
// element
private int element;
// priority
private int priority;
// Node
Node head = null, tail = null;
// returns true if the queue is empty (no items in queue)
// false if queue is (has at least one or more items in queue)
public boolean isEmpty()
{
return ( numberOfElements == 0 );
}
// returns the value of the item currently at front of queue
public int peek_frontValue()
{
return head.getValue(); // return the value in the head node
}
// returns the priority of the item currently at front of queue
public int peek_frontPriority()
{
return head.getPriority();
}
// clear the queue
public void clear()
{
head = null;
tail = null;
numberOfElements = 0;
}
// insert the item with element and priority
public void insert(int newElement, int newPriority)
{
// if head node is null, make head and tail node contain the first node
if (head == null)
{
head = new Node(newElement, newPriority);
tail=head; // when first item is enqueued, head and tail are the same
}
else
{
Node newNode = new Node(newElement, newPriority);
tail.setNext(newNode);
tail=newNode;
}
sort(newElement, newPriority);
numberOfElements++;
}
public void increase(int findElement, int priority_delta)
{
Node current = head;
if (numberOfElements > 0)
{
while (current != null)
{
if (current.getValue() == findElement)
{
int newPriority = current.getPriority() + priority_delta;
current.setIncreasePriority(newPriority);
}
current = current.getNext();
}
} else throw new UnsupportedOperationException("Empty Queue - increase failed");
}
public void decrease(int findElement, int priority_delta)
{
Node current = head;
if (numberOfElements > 0)
{
while (current != null)
{
if (current.getValue() == findElement)
{
int newPriority = current.getPriority() - priority_delta;
if (newPriority < 0)
{
throw new UnsupportedOperationException("Can't be a negative number");
}
current.setDecreasePriority(newPriority);
}
current = current.getNext();
}
} else throw new UnsupportedOperationException("Empty Queue - increase failed");
}
private void sort(int value, int priority)
{
Node current = head;
int v = value;
int p = priority;
Node temp = new Node(v, p);
if (numberOfElements > 0)
{
while (current != null && current.getNext().getPriority() < p)
{
current = current.getNext();
}
temp._next = current._next;
current._next = temp;
}
}
public int remove_maximum()
{
int headDataValue = 0;
if ( numberOfElements > 0 )
{
headDataValue = head.getValue();
Node oldHead=head;
head=head.getNext();
oldHead.setNext(null);
this.numberOfElements--;
}
else throw new UnsupportedOperationException("Empty Queue - dequeue failed");
return headDataValue; // returns the data value from the popped head, null if queue empty
}
public String display()
{
Node current = head;
String result = "";
if ( current == null )
{
result = "[Empty Queue]";
}
else
{
while ( current != null )
{
result = result + "[" + current.getValue() + "," + current.getPriority() + "] ";
current = current.getNext();
}
}
return result;
}
//////////////////////////////////////////////////////////////
// Inner Node Class
private class Node
{
private int value;
private int priority;
private Node _next;
public Node (int element, int priority_delta)
{
this.value = element;
this.priority = priority_delta;
_next = null;
}
protected Node(int element, int priority_delta, Node nextNode)
{
this.value = element;
this.priority = priority_delta;
_next = nextNode;
}
public Node getNext()
{
return _next;
}
public int getValue()
{
return this.value;
}
public int getPriority()
{
return this.priority;
}
public void setIncreasePriority(int newPriority)
{
this.priority = newPriority;
}
public void setDecreasePriority(int newPriority)
{
this.priority = newPriority;
}
public void setNext(Node newNextNode)
{
_next = newNextNode;
}
}
}
You are correct that your code currently creates duplicate nodes. Your insert method creates a node:
if (head == null) {
head = new Node(newElement, newPriority);
tail=head; // when first item is enqueued, head and tail are the same
} else {
Node newNode = new Node(newElement, newPriority);
tail.setNext(newNode);
tail=newNode;
}
This method then calls sort that also creates a node:
Node temp = new Node(v, p);
if (numberOfElements > 0) {
while (current != null && current.getNext().getPriority() < p) {
current = current.getNext();
}
temp._next = current._next;
current._next = temp;
}
It does not make a lot of sense to me that a sort method would create a new node. You should either insert the node in the right position in insert or the sort method should move it to the correct position. If you take the first approach then you'll need to change you increase and decrease methods.
A potential method to move a node to the correct position, in pseduocode, would be:
move node:
walk through queue and find both
node that's next points to the one you are moving (from)
last node that has higher priority than the one you are moving (to)
set from.next to node.next
set node.next to to.next
set to.next to node

Searching and deleting values in a circular linked list

I am trying to make an application that will loop through a circular linked list. As it does so, it will use another linked list of index values, and it will use these values to delete from the circular linked list.
I have it set up now where it should fetch the index value to be deleted from my random linked list via runRandomList() method. It then uses the rotate() method to loop through the circular linked list and deletes the value from it. It will then add the deleted value to "deletedLinked list". Then, control should return back to runRandomList() method and it should feed the rotate() method the next value from the random linked list. The circular linked list should begin traversing where it left off. It should keep track of the count and node it is on. The count should reset to 0 when it reaches the first node, so it can properly keep track of which index it is on.
Unfortunately, this is not happening. I have been trying different things for the last few days as the code stands right now; it enters into a continuous loop. the issue appears to be in the rotate method.
This is the rotate method code. My thought was the counter would advance until it matches the index input. If it reaches the first node, the counter would reset to 0 and then start to increment again until it reaches the index value.
private void rotate(int x)
{
while(counter <= x)
{
if(p == names.first)
{
counter = 0;
}
p = p.next;
counter++;
}
deleteList.add((String) p.value);
names.remove(x);
}
This is my linked list class:
public class List<T>{
/*
helper class, creates nodes
*/
public class Node {
T value;
Node next;
/*
Inner class constructors
*/
public Node(T value, Node next)
{
this.value = value;
this.next = next;
}
private Node(T value)
{
this.value = value;
}
}
/*
Outer class constructor
*/
Node first;
Node last;
public int size()
{
return size(first);
}
private int size(Node list)
{
if(list == null)
return 0;
else if(list == last)
return 1;
else
{
int size = size(list.next) + 1;
return size;
}
}
public void add(T value)
{
first = add(value, first);
}
private Node add(T value, Node list)
{
if(list == null)
{
last = new Node(value);
return last;
}
else
list.next = add(value, list.next);
return list;
}
public void setCircularList()
{
last.next = first;
}
public void show()
{
Node e = first;
while (e != null)
{
System.out.println(e.value);
e = e.next;
}
}
#Override
public String toString()
{
StringBuilder strBuilder = new StringBuilder();
// Use p to walk down the linked list
Node p = first;
while (p != null)
{
strBuilder.append(p.value + "\n");
p = p.next;
}
return strBuilder.toString();
}
public boolean isEmpty()
{
boolean result = isEmpty(first);
return result;
}
private boolean isEmpty(Node first)
{
return first == null;
}
public class RemovalResult
{
Node node; // The node removed from the list
Node list; // The list remaining after the removal
RemovalResult(Node remNode, Node remList)
{
node = remNode;
list = remList;
}
}
/**
The remove method removes the element at an index.
#param index The index of the element to remove.
#return The element removed.
#exception IndexOutOfBoundsException When index is
out of bounds.
*/
public T remove(int index)
{
// Pass the job on to the recursive version
RemovalResult remRes = remove(index, first);
T element = remRes.node.value; // Element to return
first = remRes.list; // Remaining list
return element;
}
/**
The private remove method recursively removes
the node at the given index from a list.
#param index The position of the node to remove.
#param list The list from which to remove a node.
#return The result of removing the node from the list.
#exception IndexOutOfBoundsException When index is
out of bounds.
*/
private RemovalResult remove(int index, Node list)
{
if (index < 0 || index >= size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
if (index == 0)
{
// Remove the first node on list
RemovalResult remRes;
remRes = new RemovalResult(list, list.next);
list.next = null;
return remRes;
}
// Recursively remove the element at index-1 in the tail
RemovalResult remRes;
remRes = remove(index-1, list.next);
// Replace the tail with the results and return
// after modifying the list part of RemovalResult
list.next = remRes.list;
remRes.list = list;
return remRes;
}
}
This contains the main(), runRandomList(), and rotate() methods.
public class lottery {
private int suitors;
private List<String> names;
private List<Integer> random;
private List<String> deleteList = new List<>();
private int counter;
private Node p;
public lottery(int suitors, List<String> names, List<Integer> random)
{
this.suitors = suitors;
this.names = names;
this.random = random;
p = names.first;
}
public void start()
{
//Set names list to circular
names.setCircularList();
runRandomList(random);
}
public void runRandomList(List<Integer> random)
{
Node i = random.first;
while(i != null)
{
rotate((int) i.value, counter, p);
i = i.next;
}
}
public List getDeleteList()
{
return deleteList;
}
private void rotate(int x, int count, Node p)
{
Node i = p;
while(count <= x)
{
if(i == names.first)
{
count = 0;
}
i = i.next;
count++;
}
deleteList.add((String) i.value);
names.remove(x);
p = i;
counter = count;
}
public static void main(String[] args)
{
List<String> namesList = new List<>();
namesList.add("a");
namesList.add("b");
namesList.add("c");
namesList.add("d");
namesList.add("e");
namesList.add("f");
List<Integer> randomList = new List<>();
randomList.add(3);
randomList.add(1);
randomList.add(5);
randomList.add(4);
randomList.add(0);
lottery obj = new lottery(6, namesList, randomList);
obj.start();
System.out.println(obj.getDeleteList());
}
}
As I suspected it was the rotate method, this is the solution.
private void rotate(int x, int count)
{
while(count != x)
{
p = p.next;
count++;
if(count == x)
{
deleteList.add((String)p.value);
counter = x;
}
if(count >= suitors)
{
for (int j = 0; j < x ; j++)
{
p = p.next;
}
deleteList.add((String)p.value);
counter = x;
count = x;
}
}
}

Implement a Stack with a circular singly linked list

I'm trying to implement the a Stack in Java with a circular singly linked list as the underlying data structure. I placed the insert function for a circular linked list in replacement of the push function for the stack and so on. I don't have any errors but I'm having troubles displaying the stack. If anyone could point me in the right direction of how to display the stack or what's going wrong I'd really appreciate it!
Here is my stack class:
public class Stack {
private int maxSize; // size of stack array
private long[] stackArray;
private int top; // top of stack
private Node current = null; // reference to current node
private int count = 0; // # of nodes on list
private long iData;
public Stack(int s) // constructor
{
maxSize = s; // set array size
stackArray = new long[maxSize]; // create array
top = -1; // no items yet
}
public void push(long j) // put item on top of stack
{
Node n = new Node(j);
if(isEmpty()){
current = n;
}
n.next = current;
current = n;
count++;
}
//--------------------------------------------------------------
public Node pop() // take item from top of stack
{
if(isEmpty()) {
return null;
}
else if(count == 1){
current.next = null;
current = null;
count--;
return null;
}else{
Node temp = current;
current = current.next;
temp.next = null;
temp = null;
count--;
}
return current;
}
//--------------------------------------------------------------
public Node peek(long key) // peek at top of stack
{
Node head = current;
while(head.iData != key){
head = head.next;
}
return head;
}
//--------------------------------------------------------------
public boolean isEmpty() // true if stack is empty
{
return (count == 0);
}
//--------------------------------------------------------------
public boolean isFull() // true if stack is full
{
return (count == maxSize-1);
}
//--------------------------------------------------------------
Here is my constructor class
public class Node{
public long iData; // data item (key)
public Node next; // next node in the list
public Node(long id){ // constructor
iData = id; // next automatically nulls
}
public void displayNode(){
System.out.print(iData + " ");
}
public static void main(String[] args) {
Stack newlist = new Stack(3);
newlist.push(1);
newlist.push(2);
newlist.push(3);
newlist.push(4);
newlist.pop();
newlist.pop();
newlist.push(4);
newlist.pop();
newlist.peek(1);
newlist.push(5);
while( !newlist.isEmpty() ) // until it’s empty,
{ // delete item from stack
Node value = newlist.pop();
System.out.print(value); // display it
System.out.print(" ");
} // end while
System.out.println("");
}
//newlist.displayList();
}
First, in your main function you are printing value using System.out.print function. This displays the object's class name representation, then "#" followed by its hashcode.
Replace following lines
System.out.print(value); // display it
System.out.print(" ");
with
value.displayNode();
Second, in pop method, you are returning null when count is 1. It should return the last element which is present in the list. Also, in last else if clause, you should return temp. Replace your code with this.
public Node pop() // take item from top of stack
{
if (isEmpty()) {
return null;
}
Node temp = current;
if (count == 1) {
current = null;
} else {
current = current.next;
}
count--;
temp.next = null;
return temp;
}
A few notes on your implementation:
1) stackArray member seems to be a leftover from another array based stack implementation.
2) is max size really a requirement? if so, you don't enforce the stack size limitation in push(..)
3) Your push(..) method doesn't keep the list circular. You should close the loop back to the new node.
4) Adding a dummy node allows you to keep the linked list circular, regardless of the stack size. This can make your push(..) method simpler (as well as any iteration for printing purposes for example)
5) The peek() method contract is unclear. Usually you want the peek method to return the value in the top of the stack, without removing it. Also, why do you return type Node? This class should be hidden from the caller - it's an internal implementation detail, not something you want to expose in your API.
Following is an alternative implementation, that also supports toString():
public class Stack {
private Node EOS;
private int count = 0;
public Stack() {
EOS = new Node(0);
EOS.next = EOS;
}
public void push(long j) {
Node newNode = new Node(j);
Node tmp = EOS.next;
EOS.next = newNode;
newNode.next = tmp;
count++;
}
public Long pop() {
if (isEmpty()) {
return null;
} else {
count--;
Node node = EOS.next;
EOS.next = node.next;
return node.iData;
}
}
public Long peek() {
if (isEmpty()) {
return null;
} else {
Node node = EOS.next;
return node.iData;
}
}
public boolean isEmpty() {
return (count == 0);
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
Node p = EOS.next;
while (p != EOS) {
sb.append(p).append("\n");
p = p.next;
}
return sb.toString();
}
private static class Node {
public long iData;
public Node next;
public Node(long id) {
iData = id;
}
#Override
public String toString() {
return "<" + iData + ">";
}
}
}

Java count function not working. Console application array of numbers

I am having trouble with my int count(int i) function: The function should count the number of occurrences a number appears in the List. For example there is an array of numbers 3 4 4 1 3 2 1
This is what it should display:
Item 0 count = 0
Item 1 count = 2
Item 2 count = 1
Item 3 count = 2
Item 4 count = 2
Item 5 count = 0
class Bag
{
private Node first; //dummy header node
// Initializes the list to empty creating a dummy header node.
public Bag()
{
first = new Node();
}
// Returns true if the list is empty, false otherwise
public boolean isEmpty()
{
return (first.getNext() == null);
}
// Clears all elements from the list
public void clear()
{
first.setNext(null);
}
// Returns the number of item in the list
public int getLength()
{
int length = 0;
Node current = first.getNext();
while (current != null)
{
length++;
current = current.getNext();
}
return length;
}
// Prints the list elements.
public String toString()
{
String list = "";
Node current = first.getNext();
while (current != null)
{
list += current.getInfo() + " ";
current = current.getNext();
}
return list;
}
// Adds the element x to the beginning of the list.
public void add(int x)
{
Node p = new Node();
p.setInfo(x);
p.setNext(first.getNext());
first.setNext(p);
}
// Deletes an item x from the list. Only the first
// occurrence of the item in the list will be removed.
public void remove(int x)
{
Node old = first.getNext();
Node p = first;
//Finding the reference to the node before the one to be deleted
boolean found = false;
while (old != null && !found)
{
if (old.getInfo() == x)
found = true;
else
{
p = old;
old = p.getNext();
}
}
//if x is in the list, remove it.
if (found)
p.setNext(old.getNext());
}
//public int count(int item) {
// int count = 0;
//for(int i = 0; i < length; i++) {
// if(bag[i] == item) {
// count++;
// }
//}
// return count;
//}
// Inner class Node.
private class Node
{
private int info; //element stored in this node
private Node next; //link to next node
// Initializes this node setting info to 0 and next to null
public Node()
{
info = 0;
next = null;
}
// Sets the value for this node
public void setInfo(int i)
{
info = i;
}
// Sets the link to the next node
public void setNext(Node lnk)
{
next = lnk;
}
// Returns the value in this node
public int getInfo()
{
return info;
}
// Returns the link to the next node
public Node getNext()
{
return next;
}
}
}
// Class implementing a linked list.
class LinkedList
{
private Node first; //dummy header node
// Initializes the list to empty creating a dummy header node.
public LinkedList()
{
first = new Node();
}
// Returns true if the list is empty, false otherwise
public boolean isEmpty()
{
return (first.getNext() == null);
}
// Clears all elements from the list
public void clear()
{
first.setNext(null);
}
// Returns the number of item in the list
public int getLength()
{
int length = 0;
Node current = first.getNext();
while (current != null)
{
length++;
current = current.getNext();
}
return length;
}
// Prints the list elements.
public String toString()
{
String list = "";
Node current = first.getNext();
while (current != null)
{
list += current.getInfo() + " ";
current = current.getNext();
}
return list;
}
// Adds the element x to the beginning of the list.
public void add(int x)
{
Node p = new Node();
p.setInfo(x);
p.setNext(first.getNext());
first.setNext(p);
}
// Deletes an item x from the list. Only the first
// occurrence of the item in the list will be removed.
public void remove(int x)
{
Node old = first.getNext();
Node p = first;
//Finding the reference to the node before the one to be deleted
boolean found = false;
while (old != null && !found)
{
if (old.getInfo() == x)
found = true;
else
{
p = old;
old = p.getNext();
}
}
//if x is in the list, remove it.
if (found)
p.setNext(old.getNext());
}
// Returns the element at a given location in the list
public int get(int location)
{
int item = -1;
int length = getLength();
if (location <1 || location > length)
System.out.println("\nError: Attempted get location out of range.");
else
{
int n = 1;
Node current = first.getNext();
while (n < location)
{
n++;
current = current.getNext();
}
item = current.getInfo();
}
return item;
}
/************************************************************************
Students to complete the following two methods for the LinkedList class
***********************************************************************/
// Adds item to the end of the list
public void addEnd(int item)
{
Node currentPos = new Node();
Node newPos = new Node(); //create a new node
newPos.setInfo(item); //load the data
currentPos = first;
while(currentPos.getNext() !=null)
{
currentPos = currentPos.getNext();
}
currentPos.setNext(newPos);
}
// Replaces the info in the list at location with item
public void replace(int location, int item)
{
Node currentPos = new Node();
Node prevPos = new Node();
Node nextPos = new Node();
int length = getLength();
if (location <1 || location > length)
System.out.println("\nError: Attempted get location out of range.");
else
{
prevPos = first;
for(int i=0; i < location-1; i++)
{
prevPos = prevPos.getNext();
}
currentPos = prevPos.getNext();
nextPos = currentPos.getNext();
Node newPos = new Node();
newPos.setInfo(item);
newPos.setNext(nextPos);
prevPos.setNext(newPos);
}
}
// Inner class Node.
private class Node
{
private int info; //element stored in this node
private Node next; //link to next node
// Initializes this node setting info to 0 and next to null
public Node()
{
info = 0;
next = null;
}
// Sets the value for this node
public void setInfo(int i)
{
info = i;
}
// Sets the link to the next node
public void setNext(Node lnk)
{
next = lnk;
}
// Returns the value in this node
public int getInfo()
{
return info;
}
// Returns the link to the next node
public Node getNext()
{
return next;
}
}
}
public class Lab2B2
{
public static void main(String args[])
{
Bag intBag = new Bag();
for (int i =0; i < 10; i++)
{
int info = (int)(Math.random()*10);
intBag.add(info);
}
// Before List
System.out.print("List creation before: " + intBag);
// Counts the # of occurrences of item in the bag
//System.out.println("\nCount the number of occurrences:");
//for(int i = 0; i <= 10; i++)
//{
//System.out.println("Item " + i + " count = " + list.count(i));
//}
// Returns the number of items in the bag
System.out.print("\nLength of List: " + intBag.getLength());
// Adds an item to the bag
intBag.add(9);
System.out.print("\nList creation - Add(9): " + intBag);
// Removes an item from the bag, all occurrences of item in the bag
intBag.remove(8);
System.out.print("\nList creation - Remove(8): " + intBag);
// Removes all of the items from the bag
intBag.clear();
System.out.print("\nList creation - Clear(): " + intBag);
// Determines whether the bag is empty
}
}
you are managing a LinkedList. what you need to do is run over the nodes and check if any of them equals the item you are checking for. in that case, you increase the count.
the code is full of examples how to traverse the list.
The method getLength() is a very good start as it has code that traverses all the elements. with minor modifications, you get what you want.
public int count(int item) {
int count = 0;
Node current = first.getNext();
while (current != null)
{
if (current.getInfo()==item) {
count++;
}
current = current.getNext();
}
return count;
}
Shouldn't you pass an int[] bag as an argument also, since there is no int[] bag declared as a class member?
public int count(int item, int[] bag) {
int count = 0;
for(int i = 0; i < length; i++) {
if(bag[i] == item) {
count++;
}
}
return count;
}

Categories

Resources