//Nevermind, it seems some of the testing code of my university seemed to create an infinite loop when I didnt have all methods that were part of the task implemented...
Hi guys I know this might seem a bit lazy, but the java compiler of my university claims that I have an infinite loop in my Code and I cant find it! Here's the code:
public class List {
private class Node {
private int value;
private Node next;
private Node(int element) {
this.value = element;
next = null;
}
private boolean hasNext(){
return next != null;
}
private void setNext(Node n){
next = n;
}
private Node getNext(){
return next;
}
private int getElement(){
return value;
}
}
private static void flip(Node first, Node second) {
int tmp = first.value;
first.value = second.value;
second.value = tmp;
}
private Node head;
public List() {
head = null;
}
public void add(int e){
if(head == null){
head = new Node(e);
}else{
Node n = head;
while(n.hasNext()){
n = n.getNext();
}
n.setNext(new Node(e));
}
}
#Override
public String toString() {
Node n = head;
String s = "";
while(n != null){
s += n.getElement() + " ";
n = n.getNext();
}
return s;
}
}
I basically need to program a list of integers, which seems easy to me, but already at the part of adding elements I get this error...
Related
trying to get these 2 methods to work, but I don't have much experience with generics and the concept is confusing a lot.
Anything getFirst(): Returns the value stored in the first node in the list. It should print an error message and return null if the list is empty.
Anything getLast(): Returns the value stored in the last node in the list. It should print an error message and return null if the list is empty.
Here's my code: (The methods above appear at the bottom)
public class Node<Anything>{
private Anything data;
private Node next;
Node(Anything a, Node n)
{
data = a;
next = n;
}
public Anything getData()
{
return this.data;
}
public Anything setData(Anything newData)
{
Anything oldData = this.data;
this.data = newData;
return oldData;
}
public void setNext(Node newNext)
{
this.next = newNext;
}
public Node getNext()
{
return this.next;
}
}
-----------------------------------------------
public class CS2LinkedList<Anything>{
private Node first;
private Node last;
public CS2LinkedList()
{
first = null;
}
public boolean isEmpty()
{
return (first == null);
}
public void addFirst(Anything d)
{
Node temp = first;
first = new Node(d,temp);
}
public void clear()
{
first = null;
}
public boolean contains(Anything value)
{
for (Node curr = first; curr != null; curr = curr.getNext())
{
if (value.equals(curr.getData())){
return true;
}
}
return false;
}
public String toString()
{
StringBuilder result = new StringBuilder(); //String result = "";
for (Node curr = first; curr != null; curr = curr.getNext())
result.append(curr.getData() + "->"); //result = result + curr.data + "->";
result.append("[null]");
return result.toString(); //return result + "[null]";
}
public int size()
{
int size = 0;
for (Node curr = first; curr != null; curr = curr.getNext()){
size++;
if (first==null){
size = 0;
}
}
return size;
}
// ------------------------ Question begins here ------------------------
public Anything getFirst()
{
if (first != null){
// What should I return here? I tried returning first, (Anything) first, but none of them seems to work.
}
else{
return null;
}
}
public Anything getLast()
{
if (first != null){
// Same here
}
else{
return null;
}
}
The class Node has a type parameter, but in your class CS2LinkedList you are using it without the type parameter. You're using it as a raw type. Raw types only exist in Java for backward compatibility with very old Java versions, which didn't have generics. You shouldn't use raw types (unless absolutely necessary because you have to work with very old code).
Everywhere where you write Node in your class CS2LinkedList, write Node<Anything> instead. For example, declare the member variables like this:
private Node<Anything> first;
private Node<Anything> last;
Write your addFirst method like this:
public void addFirst(Anything d)
{
Node<Anything> temp = first;
first = new Node<>(d,temp);
}
Etcetera.
Then, in you can write your getFirst() method like this:
public Anything getFirst()
{
if (first != null){
return first.getData();
}
else{
return null;
}
}
And similar for the getLast() method.
You also need to modify some of the code in class Node. The constructor parameter and the parameter of the setNext method should also have a type argument:
Node(Anything a, Node<Anything> n)
{
data = a;
next = n;
}
public void setNext(Node<Anything> newNext)
{
this.next = newNext;
}
As well as the return type of the getNext method:
public Node<Anything> getNext()
{
return this.next;
}
I'm trying to make a custom data-structure, most similar to a list, for an assignment.
I have made the class Node:
class Node {
int data;
Node nextNode = null;
public Node(int data) {
this.data=data;
}
}
and the class DataStructure:
public class DataStructure {
private Node previousNode;
private Node StartingNode;
private boolean isEmpty = true;
public void AddNode(int data) {
if(isEmpty) {
isEmpty = false;
StartingNode = new Node(data);
previousNode = StartingNode;
}
else {
previousNode.nextNode = new Node(data);
previousNode = previousNode.nextNode;
}
}
private boolean isFirst = true;
int max = 0;
public int getMaxData(Node d) {
if(isFirst) {
isFirst = false;
max = d.data;
}
else {
if(d.data > max)
max = d.data;
if(d.nextNode != null)
getMaxData(d.nextNode);
}
return max;
}
}
When I try to run an example of the above the list is not created correctly (from what I can tell). I've been thinking that it maybe has something to do with the garbage collection but I believe the node objects are still active as they are referenced by the nextNode variable.
This is the main method that runs the example:
public static void main(String [] args) {
DataStructure list = new DataStructure();
list.AddNode(5);
list.AddNode(15);
list.AddNode(12);
list.AddNode(3);
System.out.println(list.getMaxData(list.StartingNode));
}
Expected result is the number 15 to be printed but I get the first node only(5).
I tried "debugging" by adding a System.out.writeln(d.data) at the start of getMaxData() and I only get 5 printed so I believe the other nodes aren't created.
This problem is this:
if(isFirst) {
isFirst = false;
max = d.data;
} else {...}
The if will always happen for the first element, and then you just return that value. You can do it with just the else clause:
public int getMaxData(Node d) {
if (d.data > max)
max = d.data;
if (d.nextNode != null)
return getMaxData(d.nextNode);
return max;
}
public class Node {
public String name;
public Node next;
public Node(String name, Node next ){
this.name = name;
this.next = next;
}
public String getName(){
return name;
}
public void setName(String n){
name = n;
}
public Node getNext(){
return next;
}
public void setNext(Node n){
next = n;
}
public String toString() {
return "Name " + name;
}
}
public class LinkedList {
Node head = null;
int nodeCount= 0;
int counter = 0;
LinkedList(){
head = null;
}
public boolean isEmpty(){
return (head != null);
}
public void insertNode( String name ){
if( head == null){
head = new Node(name, null);
nodeCount++;
}else{
Node temp = new Node(name, null);
temp.next = head;
head = temp;
nodeCount++;
}
}
public Node reverseTest(Node L){
if(L == null || L.next ==null){
return L;
}
Node remainingNode = reverseTest(L.next);
Node cur = remainingNode;
while(cur.next !=null){
cur=cur.next;
}
L.next = null;
cur.next = L;
return remainingNode;
}
public boolean searchLinkedList(Node L, String S){
if (L == null)
return false;
else{
while(L !=null){
if(S.equals(L.name))
return true;
L= L.next;
}
}
return false;
}
public String toString(){
Node current = head;
String output = "";
while(current !=null){
output += "[" + current.getName() + "]";
current = current.getNext();
}
return output;
}
}
public class LinkedListDemo {
public static void main(String[] args){
LinkedList FriendList = new LinkedList();
FriendList.insertNode("First");
FriendList.insertNode("Second");
FriendList.insertNode("Third");
FriendList.insertNode("Fourth");
FriendList.searchLinkedList(FriendList.head, "Hello");
String NameList = FriendList.toString();
System.out.println(NameList);
System.out.println("Finish");
}
}
I have a singly linked list. I wanted to search for a value that is not present in the linkedlist and in the last loop when it reaches L = L.next I receive NPE. I don't see what is the mistake here. Please point to the right direction.
As I pointed out in the comments, there is no errors. Your IDE is just showing you its last reading of these properties.
When you get to the last loop here:
public boolean searchLinkedList(Node L, String S){
if (L == null)
return false;
else{
while(L !=null){
if(S.equals(L.name))
return true;
L= L.next;
}
}
return false;
}
L is indeed equal to null; which means that when your IDE tries to read its properties (name and next), it (and only IT, not your program's actual output) gets a reasonable NullPointerException.
The program otherwise runs fine.
Hi I am currently working on a queue wait time simultaion, over the course of 12 hours that adds a random number of people per line every minute while removing three from the front every minute as well. After the twelve hours are over i will average the rate in which they entered and exited the line. I need to perform this 50 times to get a more accurate model simulation. I do not currently know how to properly implement this. If i could get some pointers on where to begin it would be most appreciated.
Linked List Class
public class LinkedListQueue<E>{
private Node<E> head;
private Node<E> tail;
private int size;
public LinkedListQueue() {
}
public void enqueue(E element) {
Node newNode = new Node(element, null);
if (size == 0) {
head = newNode;
} else {
tail.setNextNode(newNode);
}
tail = newNode;
size++;
}
public E dequeue() {
if (head != null) {
E element = head.getElement();
head = head.getNextNode();
size--;
if (size == 0) {
tail = null;
}
return element;
}
return null;
}
public E first() {
if (head != null) {
return head.getElement();
}
return null;
}
public int getSize() {
return size;
}
public void print() {
if (head != null) {
Node currentNode = head;
do {
System.out.println(currentNode.toString());
currentNode = currentNode.getNextNode();
} while (currentNode != null);
}
System.out.println();
}
}
Node Class
public class Node<E>{
private E element;
private Node<E> next;
public Node(E element, Node next) {
this.element = element;
this.next = next;
}
public void setNextNode(Node next) {
this.next = next;
}
public Node<E> getNextNode() {
return next;
}
public E getElement() {
return element;
}
public String toString() {
return element.toString();
}
}
Simulation Class
import java.util.Random;
public class Simulation {
private int arrivalRate;
//you'll need other instance variables
public Simulation(int arrivalRate, int maxNumQueues) {
this.arrivalRate = arrivalRate;
}
public void runSimulation() {
//this is an example for using getRandomNumPeople
//you are going to remove this whole loop.
for (int i = 0; i < 10; i++) {
int numPeople = getRandomNumPeople(arrivalRate);
System.out.println("The number of people that arrived in minute " + i + " is: " + numPeople);
}
}
//Don't change this method.
private static int getRandomNumPeople(double avg) {
Random r = new Random();
double L = Math.exp(-avg);
int k = 0;
double p = 1.0;
do {
p = p * r.nextDouble();
k++;
} while (p > L);
return k - 1;
}
//Don't change the main method.
public static void main(String[] args) {
Simulation s = new Simulation(18, 10);
s.runSimulation();
}
}
It looks like you haven't started this assignment at all.
First, start with the main() method. A new Simulation object is created. Follow the constructor call to new Simulation(18, 10). For starters, you will see that the constructor is incomplete
public Simulation(int arrivalRate, int maxNumQueues) {
this.arrivalRate = arrivalRate;
// missing the handling of maxNumQueues
}
So, for starters, you probably want to define a new variable of type integer (since that is what is the type of maxNumQueues according to the Simulation constructor) in the Simulation class. From there, you obviously want to get back into the constructor and set your new variable to reference the constructor call.
Example:
public class Simulation {
private int arrivalRate;
private int maxNumQueues; // keep track of the maxNumQueues
public Simulation(int arrivalRate, int maxNumQueues) {
this.arrivalRate = arrivalRate;
this.maxNumQueues = maxNumQueues; // initialize our new local variable maxNumQueues
}}
I have been diligently watching YouTube videos in an effort to understand linked lists before my fall classes start and I am uncertain how to proceed with iterating over the following linked list. The 'node' class is from a series of videos (same author), but the 'main' method was written by me. Am I approaching the design of a linked list in an illogical fashion (assuming of course one does not wish to use the predefined LinkedList class since the professor will expect each of us to write our own implementation)?:
class Node
{
private String data;
private Node next;
public Node(String data, Node next)
{
this.data = data;
this.next = next;
}
public String getData()
{
return data;
}
public Node getNext()
{
return next;
}
public void setData(String d)
{
data = d;
}
public void setNext(Node n)
{
next = n;
}
public static String getThird(Node list)
{
return list.getNext().getNext().getData();
}
public static void insertSecond(Node list, String s)
{
Node temp = new Node(s, list.getNext());
list.setNext(temp);
}
public static int size(Node list)
{
int count = 0;
while (list != null)
{
count++;
list = list.getNext();
}
return count;
}
}
public class LL2
{
public static void main(String[] args)
{
Node n4 = new Node("Tom", null);
Node n3 = new Node("Caitlin", n4);
Node n2 = new Node("Bob", n3);
Node n1 = new Node("Janet", n2);
}
}
Thanks for the help,
Caitlin
There are some flaws in your linked list as stated by some of the other comments. But you got a good start there that grasps the idea of a linked list and looks functional. To answer your base question of how to loop over this particular implemention of the linked list you do this
Node currentNode = n1; // start at your first node
while(currentNode != null) {
// do logic, for now lets print the value of the node
System.out.println(currentNode.getData());
// proceed to get the next node in the chain and continue on our loop
currentNode = currentNode.getNext();
}
Maybe this will be useful:
static void iterate(Node head) {
Node current = head;
while (current != null) {
System.out.println(current.getData());
current = current.getNext();
}
}
// or through recursion
static void iterateRecursive(Node head) {
if (head != null) {
System.out.println(head.getData());
iterateRecursive(head.getNext());
}
}
class List {
Item head;
class Item {
String value; Item next;
Item ( String s ) { value = s; next = head; head = this; }
}
void print () {
for( Item cursor = head; cursor != null; cursor = cursor.next )
System.out.println ( cursor.value );
}
List () {
Item one = new Item ( "one" );
Item two = new Item ( "three" );
Item three = new Item ( "Two" );
Item four = new Item ( "four" );
}
}
public class HomeWork {
public static void main( String[] none ) { new List().print(); }
}
Good luck!!
You can have your linked list DS class implement 'Iterable' interface and override hasNext(), next() methods or create an inner class to do it for you. Take a look at below implementation:
public class SinglyLinkedList<T>{
private Node<T> head;
public SinglyLinkedList(){
head = null;
}
public void addFirst(T item){
head = new Node<T>(item, head);
}
public void addLast(T item){
if(head == null){
addFirst(item);
}
else{
Node<T> temp = head;
while(temp.next != null){
temp = temp.next;
}
temp.next = new Node<T>(item, null);
}
}
private static class Node<T>{
private T data;
private Node<T> next;
public Node(T data, Node<T> next){
this.data = data;
this.next = next;
}
}
private class LinkedListIterator implements Iterator<T>{
private Node<T> nextNode;
public LinkedListIterator(){
nextNode = head;
}
#Override
public boolean hasNext() {
return (nextNode.next != null);
}
#Override
public T next() {
if(!hasNext()) throw new NoSuchElementException();
T result = nextNode.data;
nextNode = nextNode.next;
return result;
}
}
}