Counting frequency of words - linked list - java

I am trying to insert words into a linked list because I want to count the number of times a word appears in the list and then return the words in the order of highest frequency to lowest. However, I keep getting an assertion error. Here are my insert, getCount, and getWords methods. It seems like insert and getCount are giving me problems.
public class Frequency<E extends Comparable<E>> implements Iterable<E>{
private Node first; //starting node
private Node parent; //parent of currently processed node
private int N; //number of words
/**
* Linked List Node
*/
private class Node{
private E key;
private int count;
private Node next;
Node(E e){
key = e;
count = 1;
next = null;
}
Node(E e, Node r){
key = e;
count = 1;
next = r;
}
#Override
public String toString(){
return "("+key +","+count+")";
}
}
/**
* Inserts a word into linked list
* #param key to be inserted
* #return true if the key is inserted successfully.
*/
public boolean insert(E key){
if (first == null || first.key != key) {
first = new Node(key, first);
} else {
Node curr = first;
while (curr.next != null) {
curr.next = new Node(key, first.next);
}
curr = curr.next;
N++;
}
return true;
}
/**
*
* #param key is the key to be searched for
* #return frequency of the key. Returns -1 if key does not exist
*
*/
public int getCount(E key){
// go through the linked list and count the number of times each word appears
// return the count of the word that is being called.
if (key == null) {
return -1;
}
int N = 0;
Node curr = first;
while (curr != null) {
if (curr.key.equals(key)) {
N++;
}
curr = curr.next;
}
return N;
}
/**
* Returns the first n words and count
* #param n number of words to be returned
* #return first n words in (word, count) format
*/
public String getWords(int n){
Node curr = first;
for (int i = 1; i < n; i++) {
curr = curr.next;
}
return curr.toString();
}
/**
* Frequency List iterator
*/
#Override
public Iterator<E> iterator() {
return new FreqIterator();
}
/**
*
* Frequency List iterator class
*
*/
private class FreqIterator implements Iterator<E>{
#Override
public boolean hasNext() {
Node curr = first;
if(curr != null) {
return true;
}
return false;
}
#Override
public E next() {
Node curr = first;
if(hasNext() == false) {
return null;
}
E item = curr.key;
curr = curr.next;
return item;
}
}
}
EDIT
This is my test to insert the same word twice into a linked list. I want the result to be 2, but I am actually getting 1. I'm assuming it has to do with my insert method.
#Test
public void testInsert() {
Frequency<String> freq = new Frequency<>();
freq.insert("dog");
freq.insert("dog");
String answer = freq.getWords(1);
assertEquals("(dog,2)", answer);
}

It doesn't work because in your getCount(E key) you never check if the key passed in is equal to the curr node while iterating through it.
Make this minor alteration to the method:
public int getCount(E key) {
if (key == null) {
return -1;
}
int N = 0;
Node curr = first;
while (curr != null) {
if (curr.key.equals(key)) { // change made here
N++;
}
curr = curr.next;
}
return N;
}
As per the edit, there is a logic error in the insert(E key). You need to iterate to find the last element in the list and then assign the next reference to the newly created node.
public boolean insert(E key) {
if (first == null || first.key != key) {
first = new Node(key, first);
} else {
Node curr = first;
while (curr.next != null) { // iterate till the end of the list
curr = curr.next;
}
curr.next = new Node(key); // point last node's next ref to new node
N++;
}
return true;
}

Related

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;
}
}
}

Deleting a node from a linked list in Java

I'm trying to write a code that handles a linked list. This linked list is somehow different because it's a key-value pair linked list (singly). The linked list should provide the user with basic functions, such as retrieving the size of linked list, checking for a key whether it's in the list or not, insertion, and deletion. It seems that all the functions are working properly except for the deletion. The code for the deletion method run correctly with no run time error, but it gives me results that's not what I wanted to have. Here is my code:
public class SequentialSearch<Key,Value> {
private int N; // number of key-value pairs
private Node head; // the linked list of key-value pairs
private Node tail;
// a helper linked list data type
private class Node {
private Key key;
private Value val;
private Node next;
public Node(Key key, Value val, Node next) {
this.key = key;
this.val = val;
this.next = next;
}
public void setNext(Node next) {
this.next = next;
}
}
public SequentialSearch() {
}
public int size() {
if (head == null)
return 0;
else {
Node x = head;
while (x.next != null) {
N++;
x = x.next;
}
}
return N;
}
public boolean isEmpty() {
return size() == 0;
}
public boolean contains(Key key) {
return get(key) != null;
}
public Value get(Key key) {
for (Node x = head; x != null; x = x.next) {
if (key.equals(x.key))
return x.val;
}
return null;
}
public void put(Key key, Value val) {
if (val == null) {
delete(key);
return;
}
for (Node x = first; x != null; x = x.next) {
if (key.equals(x.key)) {
x.val = val;
return;
}
}
first = new Node(key, val, first);
N++;
}
public boolean delete(Key key) {
Node curr = head;
Node prev = null;
boolean result = false;
if(isEmpty())
System.err.println("Error: The list is empty.");
while(curr != null) {
if(key.equals(curr.key)) {
if(curr.equals(head)) {
head = curr = null;
N--;
result = true;
return result;
} else {
prev.next = curr.next;
curr.setNext(null);
N--;
result = true;
return result;
}
} else {
prev = curr;
curr = curr.next;
}
}
return result;
}
}
I've written a main program to test for the add (put) and deletion, but it seems to be working for the insertion but not for the deletion. I think I might have a problem the deletion in case there is only one node in the list and the case of deleting a node from the middle of the list.
I'm also trying to modify the deletion method by writing a new method using the recursion, but I faced some errors -also logically. Here is the code of that function:
public void delete(Key key) {
first = delete(first, key);
}
private Node delete(Node x, Key key) {
if (x == null) return null;
if (key.equals(x.key)) {
N--;
return x.next;
}
x.next = delete(x.next, key);
return x;
}
Could you please tell me what did I do wrong?
head = curr = null;
This statement is a little confusing but I think it might be your problem for when deleting. If you're deleting a match that is at 'head', you just want to set head to 'curr.next'
What I think is going on:
delete(a)
a -> b -> c -> d
head = a
curr = a
curr.next = b
you set head to null, but head needs to point to the first item in the new list, which if you deleted 'a', would be 'b', or curr.next

Java, Creating an insert function for a LinkedList to add all inserted elements in ascending order

I have to create a linked List class from scratch for my Java project which will insert a date Object into its proper position. My format for sorting is to simply keep the year/month/day as a single string for use in comparing two Date objects. My compareTo function seems to not be the source of the problem as a simple selectionSort test yielded the proper result. My insert is simply using only the first element to compare to all the rest which is not correct. I don't know how to fix the situation after tinkering with it for some time now.
public class Date212 {
private int month;
private int day;
private int year;
public Date212(String d){
String temp;
temp = d.substring(4,6);
int theMonth = Integer.parseInt(temp);
temp = d.substring(6,8);
int theDay = Integer.parseInt(temp);
temp = d.substring(0,4);
int theYear = Integer.parseInt(temp);
setDate212(theYear, theMonth, theDay);
}
public void setDate212(int y, int m, int d){
year = y;
month = m;
day = d;
}
public int getMonth(){
return month;
}
public int getDay(){
return day;
}
public int getYear(){
return year;
}
public int compareTo(Date212 other){
if(this.toString().compareTo( ((Date212)other).toString()) < 0)
return -1; //This temp is smaller
else if(this.toString().compareTo( ((Date212)other).toString()) > 0){
return 1; //This temp is bigger
}
return 0; //Must be equal
}
public String toString(){
String s = Integer.toString(year) + "/" + Integer.toString(month) + "/" + Integer.toString(day);
return s;
}
}
public class ListNode
{
protected Date212 data;
protected ListNode next;
public ListNode(Date212 d)
{
data = d;
next = null;
} // constructor
} // class ShortNode
public class LinkedList {
/** First node in linked list - dummy node */
private ListNode first = new ListNode(null);
/** Last node in linked list */
private ListNode last = first;
/** Number of data items in the list. */
private int length = 0;
/**
* Gets the number of data values currently stored in this LinkedList.
*
* #return the number of elements in the list.
*/
public int getLength() {
return length;
}
/**
* Appends a String data element to this LinkedList.
*
* #param data
* the data element to be appended.
*/
public void append(Date212 d) {
ListNode n = new ListNode(d);
last.next = n;
last = n;
length++;
} // method append(String)
/**
* Prepends (adds to the beginning) a String data element to this
* LinkedList.
*
* #param data
* the data element to be prepended.
*/
public void insert(Date212 d) {
ListNode n = new ListNode(d);
if (length == 0) //If your list is empty
{
last = n;
first.next = n;
n.next = null;
length++;
}
else //There is element
{
ListNode p = first.next; //Start with the first element
for(int i = 0; i<length; i++){
if(p.data.compareTo(d) < 0){ //If you are smaller than the *following* element
n.next = p.next; //Insert the element after the actual
p.next = n;
return; //Return early
}
p = p.next;
}
//We are greater than any element
this.append(d);
}
}
/**
* Determines whether this ShortSequenceLinkedList is equal in value to the
* parameter object. They are equal if the parameter is of class
* ShortSequenceLinkedList and the two objects contain the same short
* integer values at each index.
*
* #param other
* the object to be compared to this ShortSequenceLinkedList
*
* #return <code>true</code> if the parameter object is a
* ShortSequenceLinkedList containing the same numbers at each index
* as this ShortSequenceLinkedList, <code>false</code> otherwise.
*/
public boolean equals(Object other) {
if (other == null || getClass() != other.getClass()
|| length != ((LinkedList) other).length)
return false;
ListNode nodeThis = first;
ListNode nodeOther = ((LinkedList) other).first;
while (nodeThis != null) {
// Since the two linked lists are the same length,
// they should reach null on the same iteration.
if (nodeThis.data != nodeOther.data)
return false;
nodeThis = nodeThis.next;
nodeOther = nodeOther.next;
} // while
return true;
} // method equals
public String printList(){
String s = "";
ListNode p = first.next;
while(p != null){
s += p.data.toString() + "\n";
p = p.next;
}
return s;
}
}// class LinkedList
Your insertion code scans up to the number of nodes recorded as the list length. That's not necessarily wrong in itself, but it would be better to just use nodes' next references to determine when you've reached the end. One reason using next would be better is that your code would be less brittle: if, say, it failed to properly manage the list length when a node was inserted before the end, then the insertion code itself would still mostly work.
Here's an alternative way your code could be written:
public void insert(Date212 d) {
ListNode n = new ListNode(d);
ListNode p = first;
// Find the insertion point
while ((p.next != null) && (p.next.data.compareTo(d) < 0)) {
p = p.next;
}
// Insert the node
n.next = p.next;
p.next = n;
if (n.next == null) {
last = n;
}
// Update the list length
length++;
}
Instead of insert at the right position I think it would be easier insert the element on the list and after sort the list like Collections.sort(myList,myComparator) does.
In a singly linked list, insertion requires a reference to the node after which the element is to be inserted. So we start with p = first, and traverse the list until we find a p.next which is greater than the element to be inserted. This means we should insert our new element after p and before p.next. This is achieved using a slightly modified version of your code as seen below.
Please note that this is for a list sorted in ascending order. For one sorted in descending order, it would be if(p.next.data.compareTo(d)<0) inside the for loop.
else //There is element
{
ListNode p = first; //Start with the head, p will point to the element AFTER which insertion should take place
for(int i = 0; i<length; i++){
if(p.next.data.compareTo(d) > 0){ //If ele to insert is lesser than next ele
n.next = p.next; //Insert the element after the actual
p.next = n;
length++;
return; //Return early
}
p = p.next;
}
//We are greater than any element
this.append(d);
}

Top 10 Gamers Linked List in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am looking for some help with a class I have designed for an assignment. It adds game scores to a linked list and lists them from highest to lowest. The max number of scores is 10. I have it almost working but I can't figure something out. I add the first score and it works, then if I add a second score, it only works if that score is higher than the first. If not, it throws a java.lang.NullPointerException. Can someone take a look at my insert(String name, int score) method and let me know what the problem is?
public class GamerList {
/**
* The node class stores a list element and a reference to the next node.
* #author johnmckillip
*
*/
private class Node {
String name;
int score;
Node next;
/**
* Constructor.
* #param val The element to store in the node.
* #param n The reference to the successor node.
*/
Node(String val1, int val2, Node n) {
name = val1;
score = val2;
next = n;
}
/**
* Constructor.
* #param val The element to store in the node.
*/
Node(String val1, int val2) {
this(val1, val2, null);
}
}
private Node head;
private Node tail;
/**
* Constructor.
*/
public GamerList() {
head = null;
tail = null;
}
/**
* The isEmpty method checks to see if the list is empty.
* #return true if the list is empty, false otherwise.
*/
public boolean isEmpty() {
return head == null;
}
/**
* The size method returns the length of the list.
* #return The number of elements in the list.
*/
public int size() {
int count = 0;
Node p = head;
while(p != null) {
count++;
p = p.next;
}
return count;
}
public void insert(String name, int score) {
Node node = new Node(name, score);
if(isEmpty()) {
head = node;
tail = node;
}
else if(head.score <= node.score) {
node.next = head;
head = node;
}
else {
Node frontPtr = head.next;
Node backPtr = head;
while(frontPtr.score > node.score && frontPtr.next != null) {
backPtr = backPtr.next;
frontPtr = frontPtr.next;
}
if(frontPtr != null && frontPtr.score <= node.score) {
backPtr.next = node;
node.next = frontPtr;
}
else {
frontPtr.next = node;
tail = node;
}
}
if(size() > 10) {
Node currentPtr = head;
while(currentPtr.next != tail) {
currentPtr = currentPtr.next;
}
tail = currentPtr;
currentPtr.next = null;
}
}
public void printList() {
Node temp = head;
while(temp != null) {
System.out.print(temp.name + " " + temp.score + " ");
System.out.println("");
temp = temp.next;
}
}
}
Here is my class to test GamerList:
public class TestGamerList {
/**
* #param args
*/
public static void main(String[] args) {
GamerList list1 = new GamerList();
list1.insert("Fry", 89);
list1.insert("Bender", 25);
list1.insert("Leela", 90);
list1.insert("Zoidburg", 23);
list1.insert("Amy", 34);
list1.insert("Hermes", 96);
list1.insert("Zapp",123);
list1.insert("Nibbler", 56);
list1.insert("Calculon", 12);
list1.insert("Hypnotoad", 189);
list1.insert("Lrrr", 5);
list1.insert("Scruffy", 28);
System.out.println("Top 10 Scores: ");
list1.printList();
}
}
Looks like you don't set head's next. That's one problem. The second is, even if you do that, you'll get into infinite loop, 'cause you have done the insertion logic incorrectly. I've changed you insert() a bit to make it work, but that still lacks elegance and is far from effective implementation. For example, on every insertion after you've got 10 elements you are running size() which makes your code complexity increase by a factor of approx. N = size(). If you really want to do that, make size a variable and just increase it at the end of every insert(). Anyway, edited code:
public class GamerList {
private class Node {
String name;
int score;
Node next;
Node(String val1, int val2, Node n) {
name = val1;
score = val2;
next = n;
}
Node(String val1, int val2) {
this(val1, val2, null);
}
}
private Node head;
private Node tail;
/**
* Constructor.
*/
public GamerList() {
head = null;
tail = null;
}
/**
* The isEmpty method checks to see if the list is empty.
* #return true if the list is empty, false otherwise.
*/
public boolean isEmpty() {
return head == null;
}
/**
* The size method returns the length of the list.
* #return The number of elements in the list.
*/
public int size() {
int count = 0;
Node p = head;
while(p != null) {
count++;
p = p.next;
}
return count;
}
public void insert(String name, int score) {
Node node = new Node(name, score);
if(isEmpty()) {
head = node;
head.next = tail;
}
else if(head.score <= node.score) {
node.next = head;
head = node;
}
else {
Node beforeNode = head;
while(beforeNode.score > node.score && beforeNode.next != null) {
beforeNode = beforeNode.next;
}
node.next = beforeNode.next;
beforeNode.next = node;
}
if(size() > 10) {
Node currentPtr = head;
for (int i = 0; i < 9; i++) {
currentPtr = currentPtr.next;
}
currentPtr.next = null;
}
}
public void printList() {
Node temp = head;
while(temp != null) {
System.out.print(temp.name + " " + temp.score + " ");
System.out.println("");
temp = temp.next;
}
}
}
Without stack trace is complex.
but probably error is here
while(frontPtr.score > node.score && frontPtr.next != null)
since frontPtr is null.
add a check on the
if (frontPtr!=null)
while(frontPtr.score > node.score && frontPtr.next != null)

Categories

Resources