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;
}
Related
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
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.
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;
}
}
}
So for my assignment we are to implement some referenced based list manipulation methods in a class and then add to a list and demonstrate the methods using a driver file.
I have provided the entire program for download which includes a pdf that explains the assignment. Our professor uploaded a completed driver file and mine is exactly the same as his but I am getting some run-time errors, first is when calling add() for the third time I get a NullPointerException, if I comment out the rest of the add() calls, size() will not return the same size as getSize() and getSizeRecursive().
Please Help me. Link to download: https://www.dropbox.com/s/qe771q3156h9nwx/ListReferenceBased.rar
// ****************************************************
// Reference-based implementation of ADT list.
// ****************************************************
public class ListReferenceBased implements ListInterface {
// reference to linked list of items
private Node head;
private int numItems; // number of items in list
public ListReferenceBased() {
numItems = 0;
head = null;
} // end default constructor
public boolean isEmpty() {
return numItems == 0;
} // end isEmpty
public int size() {
return numItems;
} // end size
private Node find(int index) {
// --------------------------------------------------
// Locates a specified node in a linked list.
// Precondition: index is the array index of the desired node.
// Assumes that 0 <= index < numItems
// Postcondition: Returns a reference to the desired node.
// --------------------------------------------------
Node curr = head;
for (int skip = 0; skip < index; skip++) {
curr = curr.getNext();
} // end for
return curr;
} // end find
public Object get(int index)
throws ListIndexOutOfBoundsException {
if (index >= 0 && index < numItems) {
// get reference to node, then data in node
Node curr = find(index);
Object dataItem = curr.getItem();
return dataItem;
}
else {
throw new ListIndexOutOfBoundsException(
"List index out of bounds on get");
} // end if
} // end get
public void add(int index, Object item)
throws ListIndexOutOfBoundsException {
if (index >= 0 && index <= numItems) {
if (index == 0) {
// insert the new node containing item at
// beginning of list
Node newNode = new Node(item, head);
head = newNode;
}
else {
Node prev = find(index-1);
// insert the new node containing item after
// the node that prev references
Node newNode = new Node(item, prev.getNext());
prev.setNext(newNode);
} // end if
numItems++;
}
else {
throw new ListIndexOutOfBoundsException(
"List index out of bounds on add");
} // end if
} // end add
public void remove(int index)
throws ListIndexOutOfBoundsException {
if (index >= 0 && index < numItems) {
if (index == 0) {
// delete the first node from the list
head = head.getNext();
}
else {
Node prev = find(index-1);
// delete the node after the node that prev
// references, save reference to node
Node curr = prev.getNext();
prev.setNext(curr.getNext());
} // end if
numItems--;
} // end if
else {
throw new ListIndexOutOfBoundsException(
"List index out of bounds on remove");
} // end if
} // end remove
public void removeAll() {
// setting head to null causes list to be
// unreachable and thus marked for garbage
// collection
head = null;
numItems = 0;
} // end removeAll
// TO IMPLEMENT
public String toString(){
Node curr = head;
String str = new String("");
while(curr != null){
str += curr.getItem() + ", ";
curr = curr.getNext();
}
return str;
}
// TO IMPLEMENT
public void reverse(){
Node prev = null;
Node curr = head;
while(curr != null){
Node next = curr.getNext();
curr.setNext(prev);
prev = curr;
curr = next;
}
head = prev;
}
// TO IMPLEMENT
// This is a helper method, so try to define your own method
// that this helper will call.
public void reverseRecursive(){
Node prev = null;
Node curr = head;
reverseRecursiveHelper(prev, curr);
head = prev;
}
public Object reverseRecursiveHelper(Node prev, Node curr){
if(curr == null)
return null;
else {
Node next = curr.getNext();
curr.setNext(prev);
prev = curr;
curr = next;
return reverseRecursiveHelper(prev, curr);
}
}
// TO IMPLEMENT
public int getSize()
// --------------------------------------------------
// Returns the number of items in a linked list.
// Precondition: head points to the first element
// in a list of type node.
// Postcondition: The number of items in the list
// is returned.
// --------------------------------------------------
{
int count = 0;
Node curr = head;
while(curr != null){
curr = curr.getNext();
count++;
}
return count;
}
// TO IMPLEMENT
public int getSize(Node cur)
// --------------------------------------------------
// Returns the number of items in a linked list.
// The initial call should have the beginning of the list
// as it's input argument, i.e. listCount(head);
// Precondition: cur points to a list of type node
// Postcondition: The number of items in the list
// is returned.
// --------------------------------------------------
{
if(cur != null)
return 1 + getSize(cur.getNext());
else //base case
return 0;
}
// TO IMPLEMENT
public int getSizeRecursive()
{
return getSize(head);
}
// TO IMPLEMENT
public Node findMToLast(int m){
Node current = head;
if(current == null)
return null;
for(int i = 0; i < m; i++)
if(current.getNext() != null)
current = current.getNext();
else
return null;
Node mBehind = head;
while (current.getNext() != null){
current = current.getNext();
mBehind = mBehind.getNext();
}
return mBehind;
}
} // end ListReferenceBased
Driver:
// ********************************************************
// Test Reference-based implementation of the ADT list.
// *********************************************************
public class TestListReferenceBased {
static public void main(String[] args)
{
ListReferenceBased aList = new ListReferenceBased();
aList.add(0, new Integer(1));
aList.add(1, new Integer(2));
aList.add(2, new Integer(3));
aList.add(3, new Integer(4));
aList.add(4, new Integer(5));
aList.add(5, new Integer(6));
System.out.println("size() and get(i): ");
for (int i = 0; i < aList.size(); i++)
System.out.println(aList.get(i) + " ");
System.out.println();
System.out.println("Size with size() = " + aList.size());
System.out.println("Size with getSize() = " + aList.getSize());
System.out.println("Size with getSizeRecursive() = " + aList.getSizeRecursive());
System.out.println("Initial List = " + aList);
aList.reverse(); // iterative version
System.out.println("Reverse with reverse() = " + aList);
System.out.println("====================================");
aList.reverseRecursive(); // recursive version
System.out.println("Reverse with reverseRecursive() = " + aList);
int offset = 3;
Node node = aList.findMToLast(offset);
if (node != null)
System.out.println(offset + "-th node to the last node contains " + node.getItem() + ".");
else
System.out.println("Offset(=" + offset + ") to the last node is greater than list size(=" + aList.size() + ").");
} // end main
} // end TestListReferenceBased
Stack trace is:
Exception in thread "main" java.lang.NullPointerException at
ListReferenceBased.add(ListReferenceBased.java:63) at
TestListReferenceBased.main(TestListReferenceBased.java:14)
I'm trying to work on a method that will insert the node passed to it before the current node in a linked list. It has 3 conditions. For this implementation there cannot be any head nodes (only a reference to the first node in the list) and I cannot add any more variables.
If the list is empty, then set the passed node as the first node in the list.
If the current node is at the front of the list. If so, set the passed node's next to the current node and set the first node as the passed node to move it to the front.
If the list is not empty and the current is not at the front, then iterate through the list until a local node is equal to the current node of the list. Then I carry out the same instruction as in 2.
Here is my code.
public class LinkedList
{
private Node currentNode;
private Node firstNode;
private int nodeCount;
public static void main(String[] args)
{
LinkedList test;
String dataTest;
test = new LinkedList();
dataTest = "abcdefghijklmnopqrstuvwxyz";
for(int i=0; i< dataTest.length(); i++) { test.insert(new String(new char[] { dataTest.charAt(i) })); }
System.out.println("[1] "+ test);
for(int i=0; i< dataTest.length(); i++) { test.deleteCurrentNode(); }
System.out.println("[2] "+test);
for(int i=0; i< dataTest.length(); i++)
{
test.insertBeforeCurrentNode(new String(new char[] { dataTest.charAt(i) }));
if(i%2 == 0) { test.first(); } else { test.last(); }
}
System.out.println("[3] "+test);
}
public LinkedList()
{
setListPtr(null);
setCurrent(null);
nodeCount = 0;
}
public boolean atEnd()
{
checkCurrent();
return getCurrent().getNext() == null;
}
public boolean isEmpty()
{
return getListPtr() == null;
}
public void first()
{
setCurrent(getListPtr());
}
public void next()
{
checkCurrent();
if (atEnd()) {throw new InvalidPositionInListException("You are at the end of the list. There is no next node. next().");}
setCurrent(this.currentNode.getNext());
}
public void last()
{
if (isEmpty()) {throw new ListEmptyException("The list is currently empty! last()");}
while (!atEnd())
{
setCurrent(getCurrent().getNext());
}
}
public Object getData()
{
return getCurrent().getData();
}
public void insertBeforeCurrentNode(Object bcNode) //beforeCurrentNode
{
Node current;
Node hold;
boolean done;
hold = allocateNode();
hold.setData(bcNode);
current = getListPtr();
done = false;
if (isEmpty())
{
setListPtr(hold);
setCurrent(hold);
}
else if (getCurrent() == getListPtr())
{
System.out.println("hi" + hold);
hold.setNext(getCurrent());
setListPtr(hold);
}
else //if (!isEmpty() && getCurrent() != getListPtr())
{
while (!done && current.getNext() != null)
{
System.out.println("in else if " + hold);
if (current.getNext() == getCurrent())
{
//previous.setNext(hold);
//System.out.println("hi"+ "yo" + " " + getListPtr());
hold.setNext(current.getNext());
current.setNext(hold);
done = true;
}
//previous = current;
current = current.getNext();
}
}
System.out.println(getCurrent());
}
public void insertAfterCurrentNode(Object acNode) //afterCurrentNode
{
Node hold;
hold = allocateNode();
hold.setData(acNode);
if (isEmpty())
{
setListPtr(hold);
setCurrent(hold);
//System.out.println(hold + " hi");
}
else
{
//System.out.println(hold + " hia");
hold.setNext(getCurrent().getNext());
getCurrent().setNext(hold);
}
}
public void insert(Object iNode)
{
insertAfterCurrentNode(iNode);
}
public Object deleteCurrentNode()
{
Object nData;
Node previous;
Node current;
previous = getListPtr();
current = getListPtr();
nData = getCurrent().getData();
if (isEmpty()) {throw new ListEmptyException("The list is currently empty! last()");}
else if (previous == getCurrent())
{
getListPtr().setNext(getCurrent().getNext());
setCurrent(getCurrent().getNext());
nodeCount = nodeCount - 1;
}
else
{
while (previous.getNext() != getCurrent())
{
previous = current;
current = current.getNext();
}
previous.setNext(getCurrent().getNext());
setCurrent(getCurrent().getNext());
nodeCount = nodeCount - 1;
}
return nData;
}
public Object deleteFirstNode(boolean toDelete)
{
if (toDelete)
{
setListPtr(null);
}
return getListPtr();
}
public Object deleteFirstNode()
{
Object deleteFirst;
deleteFirst = deleteFirstNode(true);
return deleteFirst;
}
public int size()
{
return this.nodeCount;
}
public String toString()
{
String nodeString;
Node sNode;
sNode = getCurrent();
//System.out.println(nodeCount);
nodeString = ("List contains " + nodeCount + " nodes");
while (sNode != null)
{
nodeString = nodeString + " " +sNode.getData();
sNode = sNode.getNext();
}
return nodeString;
}
private Node allocateNode()
{
Node newNode;
newNode = new Node();
nodeCount = nodeCount + 1;
return newNode;
}
private void deAllocateNode(Node dNode)
{
dNode.setData(null);
}
private Node getListPtr()
{
return this.firstNode;
}
private void setListPtr(Node pNode)
{
this.firstNode = pNode;
}
private Node getCurrent()
{
return this.currentNode;
}
private void setCurrent(Node cNode)
{
this.currentNode = cNode;
}
private void checkCurrent()
{
if (getCurrent() == null) {throw new InvalidPositionInListException("Current node is null and is set to an invalid position within the list! checkCurrent()");}
}
/**NODE CLASS ----------------------------------------------*/
private class Node
{
private Node next; //serves as a reference to the next node
private Object data;
public Node()
{
this.next = null;
this.data = null;
}
public Object getData()
{
return this.data;
}
public void setData(Object obj)
{
this.data = obj;
}
public Node getNext()
{
return this.next;
}
public void setNext(Node nextNode)
{
this.next = nextNode;
}
public String toString()
{
String nodeString;
Node sNode;
sNode = getCurrent();
//System.out.println(nodeCount);
nodeString = ("List contains " + nodeCount + " nodes");
while (sNode != null)
{
nodeString = nodeString + " " +sNode.getData();
sNode = sNode.getNext();
}
return nodeString;
}
}
}
I have it working for my [1] and [2] conditions. But my [3] (that tests insertBeforeCurrentNode()) isn't working correctly. I've set up print statements, and I've determined that my current is reset somewhere, but I can't figure out where and could use some guidance or a solution.
The output for [1] and [2] is correct. The output for [3] should read
[3] List contains 26 nodes: z x v t r p n l j h f d b c e g i k m o q s u w y a
Thanks for any help in advance.
In your toString method you start printing nodes from the currentNode till the end of your list. Because you call test.last() just before printing your results, the currentNode will point on the last node of the list, and your toString() will only print 'a'.
In your toString() method, you may want to change
sNode = getCurrent();
with
sNode = getListPtr();
to print your 26 nodes.
For [3] you need to keep pointers to two nodes: one pointer in the "current" node, the one you're looking for, and the other in the "previous" node, the one just before the current. In that way, when you find the node you're looking in the "current" position, then you can connect the new node after the "previous" and before the "current". In pseudocode, and after making sure that the cases [1] and [2] have been covered before:
Node previous = null;
Node current = first;
while (current != null && current.getValue() != searchedValue) {
previous = current;
current = current.getNext();
}
previous.setNext(newNode);
newNode.setNext(current);