I wish to implement a Queue based in a simple linked list class, without using java.util.
When I call the addEnd method in List class through enqueue method, I receive a java.lang.NullPointerException, though I expect the second element.
Which solution can I take?
The node class
public class Node {
private int value;
private Node next;
public Node(int val) {
value = val;
}
public Node(int val, Node next) {
value = val;
this.next=next;
}
public Node(Node next) {
this.next=next;
}
public int getValue() {
return value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public void displayNode() {
System.out.print(" "+value+" ");
}
}
My interface
public interface MyQueue {
void enqueue(int oVal);
int dequeue();
}
The List
public class List {
private Node first;
private Node last;
private int counter;
public List() {
first = null;
last = null;
}
public boolean isEmpty() {
return first==null;
}
public void addEnd(int val) {
Node n1 = new Node(val);
if( isEmpty() ) {
first = n1;
} else {
last.setNext(n1);
last = n1;
}
}
public int deleteStart() {
int temp = first.getValue();
if(first.getNext() == null){
last = null;
first = first.getNext();
}
return temp;
}
public void displayList() {
Node current = first;
while(current != null) {
current.displayNode();
current = current.getNext();
}
System.out.println("");
}
public int size() {
return counter;
}
}
The Queue
public class Queue implements MyQueue {
private List listQ;
public Queue() {
listQ = new List();
}
public boolean isEmpty() {
return listQ.isEmpty();
}
public void enqueue(int oVal) {
listQ.addEnd(oVal);
}
public int dequeue() {
return listQ.deleteStart();
}
public void displayQueue() {
System.out.print("Queue ");
listQ.displayQueue();
}
}
public class App {
public static void main(String[] args) {
Queue q1 = new Queue();
System.out.println("Two insertions");
q1.enqueue(4);
q1.enqueue(64);
q1.displayQueue();
System.out.println("Insert at the end : ");
q1.enqueue(23);
q1.displayQueue();
System.out.println("Delete an element at the begining of the queue");
q1.dequeue();
q1.displayQueue();
}
}
What #pens-fan-69 said is true. I'd like to add on to that. In order to make your code work, all you have to do is make sure last is set to first during the first insert:
public void addEnd(int val) {
Node n1 = new Node(val);
if( isEmpty() ) {
first=last=n1;
} else {
last.setNext(n1);
last = n1;
}
}
I tried running the code in online compiler and it works: http://goo.gl/99FyfY
You need to set the last reference when inserting to the empty list. The NullPointerException is because you use last before ever setting it.
Related
I want to reverse a linked list . I am able to reverse the list but in doing so, original list is also affected .How to see both original and reverse linkedlist while using display function?
Asking for the below codebase...
Please help with the display and reverseLink method . Added all the other classes as well.
public class Node {
int data;
Node link;
public Node(int data, Node link) {
this.data = data;
this.link = link;
}
public Node() {
this.data = 0;
this.link = null;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getLink() {
return link;
}
public void setLink(Node link) {
this.link = link;
}
}
public class Sa_LinkedList {
Node start;
Node end;
int size;
public Sa_LinkedList() {
start=null;
end=null;
size=0;
}
public boolean isEmpty() {
return start==null;
}
public int getSize() {
return size;
}
public void insertAtStart(int val) {
Node newNd=new Node(val,null);
size++;
if(start==null) {
start=newNd;
end=start;
}
else
{
newNd.setLink(start);
start=newNd;
}
}
public void insertAtEnd(int val) {
Node newNd=new Node(val,null);
size++;
if(end==null) {
end=start=newNd;
}
else {
end.setLink(newNd);
end=newNd;
}
}
public void insertAtPos(int val,int pos) {
Node newNd=new Node(val,null);
Node ptr=start;
pos=pos-1;
for(int i=0;i<size;i++) {
if(i==pos) {
Node temp=ptr.getLink();
ptr.setLink(newNd);
newNd.setLink(temp);
break;
}
ptr=ptr.getLink();
}
size++;
}
public void deleteAtPos(int pos) {
if(pos==1) {
start=start.getLink();
size--;
return;
}
if(pos==size) {
Node s=start;
Node t=start;
while(t!=end) {
s=t;
t=t.getLink();
}
end=s;
end.setLink(null);
size--;
return;
}
Node ptr=start;
pos=pos-1;
for(int i=0;i<size;i++) {
if(i==pos) {
Node temp=ptr.getLink();
temp=temp.getLink();
ptr.setLink(temp);
break;
}
ptr=ptr.getLink();
}
size--;
}
//*Function for displaying the linkedlist
public void display() {
System.out.println("Displaying the linkedlist elements:");
Node ptr=start;
if (size==0)
{
System.out.println("sorry...------List is empty------");
return;
}
if(start.getLink()==null)
{
System.out.println(start.getData());
return;
}
while(ptr.getLink()!=null) {
System.out.println(ptr.getData()+",");
ptr=ptr.getLink();
}
System.out.println(ptr.getData()+"\n");
}
public void reverseLink() {
Node current=start;
Node next=null;
Node prev=null;
while(current!=null) {
next=current.getLink();
current.setLink(prev);
prev=current;
current=next;
}
start=prev;
}
}
There is Collections.reverse(List) method available in JDK. You could us its approach as an example:
public static void reverse(List<?> list) {
int size = list.size();
if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)
swap(list, i, j);
} else {
// instead of using a raw type here, it's possible to capture
// the wildcard but it will require a call to a supplementary
// private method
ListIterator fwd = list.listIterator();
ListIterator rev = list.listIterator(size);
for (int i=0, mid=list.size()>>1; i<mid; i++) {
Object tmp = fwd.next();
fwd.set(rev.previous());
rev.set(tmp);
}
}
}
Copy the list and reverse one or
or build a Doubly linked list. In a Doubly linked list each node knows its previous and next node. With this you can easily print the list in reversed order
created java linked list to add some data. want to compare first data inside that linked list. when i use peek() it not working. any other way to get front element and compare or how to write peek() method
LinkList class :
package list;
public class LinkList {
private class Node<T> {
public final T data;
public Node next;
public Node(T data) {
this.data = data;
}
public void displayNode() {
System.out.print(data + " ");
}
}
public static Node first = null;
private Node last = null;
public boolean isEmpty() {
return (first == null);
}
public <T> void addLast(T data) {
Node n = new Node(data);
if (isEmpty()) {
n.next = first;
first = n;
last = n;
} else {
last.next = n;
last = n;
last.next = null;
}
}
public void removeFirst() {
Node temp = first;
if (first.next == null) {
last = null;
}
first = first.next;
}
public void displayList() {
Node current = first;
while (current != null) {
current.displayNode();
current = current.next;
}
}
}
LinkListQueue:
package list;
public class LinkListQueue {
LinkList newLinkList = new LinkList();
public <T> void enqueue(T data) {
newLinkList.addLast(data);
}
public void dequeue() {
if (!newLinkList.isEmpty()) {
newLinkList.removeFirst();
}
}
public String displayQueue() {
newLinkList.displayList();
System.out.println();
return "";
}
public boolean isEmpty() {
return newLinkList.isEmpty();
}
}
LinkListQueueMain :
package list;
public class LinkListqueueMain {
public String getValue=null;
public static String displayQ = null;
static LinkListQueue queueImpl = new LinkListQueue();
static LinkList linkList = new LinkList();
public static void main(String[] args) {
runData();
}
public static void runData() {
queueImpl.enqueue("80%");
queueImpl.enqueue("70%");
queueImpl.enqueue("60%");
queueImpl.enqueue("85%");
queueImpl.enqueue("45%");
queueImpl.enqueue("55%");
for (int i = 0; i < 5; i++) {
System.out.println(linkList.toString());
}
}
}
This is my code. Any idea how to do that?
First you need to paramtrize the LinkList, not necessarily the node, as the LinkList is the public API to the outer world.
public class LinkList<T> {
private static class Node {
Then you could return the removed value. (removeFirst can throw a NullPointerException on an empty list.)
public T removeFirst() {
T removed = first.data;
if (first.next == null) {
last = null;
}
first = first.next;
return removed;
}
public T peekFirst() {
return first.data;
}
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 LinkedList with test program. As you can see in that program I add some Students to the list. I can delete them. If I choose s1,s2,s3 oraz s4 to delete everything runs well, and my list is printed properly and information about number of elements is proper. But if I delete last element (in this situation - s5) info about number of elements is still correct, but this element is still printed. Why is that so? Where is my mistake?
public class Lista implements List {
private Element head = new Element(null); //wartownik
private int size;
public Lista(){
clear();
}
public void clear(){
head.setNext(null);
size=0;
}
public void add(Object value){
if (head.getNext()==null) head.setNext(new Element(value));
else {
Element last = head.getNext();
//wyszukiwanie ostatniego elementu
while(last.getNext() != null)
last=last.getNext();
// i ustawianie jego referencji next na nowowstawiany Element
last.setNext(new Element(value));}
++size;
}
public Object get(int index) throws IndexOutOfBoundsException{
if(index<0 || index>size) throw new IndexOutOfBoundsException();
Element particular = head.getNext();
for(int i=0; i <= index; i++)
particular = particular.getNext();
return particular.getValue();
}
public boolean delete(Object o){
if(head.getNext() == null) return false;
if(head.getNext().getValue().equals(o)){
head.setNext(head.getNext().getNext());
size--;
return true;
}
Element delete = head.getNext();
while(delete != null && delete.getNext() != null){
if(delete.getNext().getValue().equals(o)){
delete.setNext(delete.getNext().getNext());
size--;
return true;
}
delete = delete.getNext();
}
return false;
}
public int size(){
return size;
}
public boolean isEmpty(){
return size == 0;
}
public IteratorListowy iterator() {
return new IteratorListowy();
}
public void wyswietlListe() {
IteratorListowy iterator = iterator();
for (iterator.first(); !iterator.isDone(); iterator.next())
{
System.out.println(iterator.current());
}
System.out.println();
}
public void infoOStanie() {
if (isEmpty()) {
System.out.println("Lista pusta.");
}
else
{
System.out.println("Lista zawiera " + size() + " elementow.");
}
}
private static final class Element{
private Object value;
private Element next; //Referencja do kolejnego obiektu
public Element(Object value){
setValue(value);
}
public void setValue(Object value) {
this.value = value;
}
public Object getValue() {
return value;
}
//ustawia referencję this.next na obiekt next podany w atgumencie
public void setNext(Element next) {
if (next != null)
this.next = next;
}
public Element getNext(){
return next;
}
}
private class IteratorListowy implements Iterator{
private Element current;
public IteratorListowy() {
current = head;
}
public void next() {
current = current.next;
}
public boolean isDone() {
return current == null;
}
public Object current() {
return current.value;
}
public void first() {
current = head.getNext();
}
}
}
test
public class Program {
public static void main(String[] args) {
Lista lista = new Lista();
Iterator iterator = lista.iterator();
Student s1 = new Student("Kowalski", 3523);
Student s2 = new Student("Polański", 45612);
Student s3 = new Student("Karzeł", 8795);
Student s4 = new Student("Pałka", 3218);
Student s5 = new Student("Konowałek", 8432);
Student s6 = new Student("Kłopotek", 6743);
Student s7 = new Student("Ciołek", 14124);
lista.add(s1);
lista.add(s2);
lista.add(s3);
lista.add(s4);
lista.add(s5);
lista.wyswietlListe();
lista.delete(s5);
lista.wyswietlListe();
lista.infoOStanie();
lista.clear();
lista.infoOStanie();
}
}
The problem is that your setNext(Element next) method does not set anything if next == null. And that is the case for the last element of your list.
So when you call delete.setNext(delete.getNext().getNext());, nothing is actually set because delete.getNext().getNext() is null!
Remove the if (next != null) condition in setNext and it will work.
I was designing a generic linked list to create a linked list of Strings.
However I keep getting this error :
Exception in thread "main" java.lang.NoSuchMethodError: Node.<init>(Ljava/lang/Object;)V
at LinkedList.addNode(LinkedList.java:10)
at LinkedList.<init>(LinkedList.java:22)
at Trial.main(Trial.java:7)
From the stack trace , the error is generated at LinkedList's addNode() method. Im including the definition to this method as well as the definition of the Node class.
LinkedList addNode()
public void addNode(T n) {
Node<T> temp = new Node<T>(n);
if(start==null) {
start = temp;
current = start;
} else {
end.setNext(temp);
}
end =temp;
}
Node.java
public class Node<T>{
private T n;
Node next;
Node(T n) {
this.n = n;
next = null;
}
public void setNext(Node nextNode) {
next = nextNode;
}
public Node getNext() {
return next;
}
public T getN() {
return n;
}
#Override
public String toString() {
if(n instanceof String)
return n.toString();
else {
return T.toString();
}
}
}
LinkedList.java
public class LinkedList<T>{
Node start;
Node end;
Node current;
private static final long serialVersionUID = 901L;
LinkedList(T n) {
addNode(n);
}
public void addNode(T n) {
Node<T> temp = new Node<>(n);
if(start==null) {
start = temp;
current = start;
} else {
end.setNext(temp);
}
end =temp;
}
LinkedList(T[] n) {
for(T print : n)
addNode(print);
}
public void addNode(T[] n) {
if(n!=null) {
for (T values : n) {
addNode(values);
}
}
}
public void incC() {
current = current.getNext();
}
public void insert(T n) {
Node newNode = new Node(n);
if(current==start){
newNode.setNext(current);
start = newNode;
}else {
Node tempstart = start;
Node prevAdd=null;
while(tempstart!=current){
prevAdd = tempstart;
tempstart = tempstart.getNext();
}
prevAdd.setNext(newNode);
newNode.setNext(current);
}
}
public void find(T x) {
Node tempstart;
tempstart = start;
while (tempstart!=null) {
if(tempstart.getN()==x) {
System.out.println("Element found");
tempstart = tempstart.getNext();
} else {
tempstart = tempstart.getNext();
}
}
}
public void delete(T x) {
Node previous=null;
Node tempstart = start;
while(tempstart!=null) {
if(tempstart.getN()==x) {
if(previous ==null) {
previous = tempstart;
tempstart = tempstart.getNext();
start = tempstart;
previous.setNext(null);
previous = null;
} else {
tempstart = tempstart.getNext();
previous.setNext(tempstart);
}
}else {
previous = tempstart;
tempstart = tempstart.getNext();
}
}
}
#Override
public String toString() {
Node tempNode = start;
String str = "Values: ";
while (tempNode!=null) {
str = str + " " + tempNode.toString();
tempNode = tempNode.getNext();
}
return str;
}
}
Trial.java
public class Trial {
public static void main(String[] args) {
String[] para = {"Hollo","this","is","me"};
LinkedList<String> L1;
L1 = new LinkedList<String>(para);
System.out.println(L1);
}
return T.toString();
this doesn't work. T is a type variable and only available at compile time due to type erasure.
But apart from that, I can't see what's wrong, you need to poost more code from your LinkedList class.
You should declare the start, end, and current fields in LinkedList< T > and the next field in Node< T > as type Node< T >, not Node. Don't use raw types anywhere in the code, because they translate into Node< Object >.
Your class Nodedoes not compile, so it is likely that you should first fix that issue before continuing:
return T.toString();
does not make sense. Probably that just writing this:
return n.toString();
is enough for now.
In Node.java, in the method
#Override
public String toString() {
if(n instanceof String)
return n.toString();
else {
return T.toString();
}
}
// the below statement thows compilation error.
return T.toString();
Your Node Constructor is not public, so it will not work if you call it from a class in another package.