import java.awt.HeadlessException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import javax.xml.soap.Node;
public class Deque<Item> implements Iterable<Item> {
private int size;
private Node<Item> head;
private Node<Item> tail;
private static class Node<Item> {
private Item key;
private Node<Item> leftNode;
private Node<Item> rightNode;
Node(Item key, Node<Item> left, Node<Item> right) {
this.key = key;
this.leftNode = left;
this.rightNode = right;
}
}
public Deque() {
head = new Node<Item>(null,null,null);
tail = new Node<Item>(null,head,null);
head.rightNode = tail;
size = 0;
}
public boolean isEmpty() {
return head.rightNode == tail;
}
public int size() {
return size;
}
public void addFirst(Item item) {
if (item == null) throw new NullPointerException(" trying to add nothing");
else {
Node<Item> oldFirstNode = head.rightNode;
head.rightNode = new Node<Item>(item,head,oldFirstNode);
oldFirstNode.leftNode = head.rightNode;
size++;
}
}
public void addLast(Item item) {
if (item == null) throw new NullPointerException(" trying to add nothing");
else {
Node<Item> oldLastNode = tail.leftNode;
tail.leftNode = new Node<Item>(item,oldLastNode,tail);
oldLastNode.rightNode = tail.leftNode;
size++;
}
}
public Item removeFirst() { // remove and return the item from the front
if (isEmpty()) throw new NoSuchElementException(" Deque is alrady empty");
else {
Node<Item> delete = head.rightNode;
Node<Item> newFirstNode = head.rightNode.rightNode;
newFirstNode.leftNode = head;
head.rightNode = newFirstNode;
delete.leftNode = null;
delete.rightNode = null;
Item myKeyItem = delete.key;
delete = null;
size--;
return myKeyItem;
}
}
public Item removeLast() { // remove and return the item from the end
if (isEmpty()) throw new NoSuchElementException(" Deque is alrady empty");
else {
Node<Item> delete = tail.leftNode;
Node<Item> newLastNode = tail.leftNode.leftNode;
newLastNode.rightNode = tail;
tail.leftNode = newLastNode;
delete.leftNode = null;
delete.rightNode = null;
Item myKeyItem = delete.key;
delete = null;
size--;
return myKeyItem;
}
}
public Iterator<Item> iterator() { // return an iterator over items in order from front to end
return new DequeIterator();
}
private class DequeIterator implements Iterator<Item> {
private Node<Item> current = head.rightNode;
public boolean hasNext() {return current != tail;}
public void remove() { throw new UnsupportedOperationException("not yet"); }
public Item next() {
if (!hasNext()) throw new NoSuchElementException("no next");
Item key = current.key;
current = current.rightNode;
return key;
}
}
public static void main(String[] args) {
Deque<Integer>[] s = new Deque[10];
for (int i = 0; i < 10; i++) {
s[i] =new Deque<Integer>(); // initial each object
}
s[0].addFirst(1);
// s[1].addFirst(2);
StdOut.print(s[0]);
//StdOut.print(s[1]);
}
}
In the following code I have a compiling error stats that "Cannot instantiate the type Deque".
package Assign3;
import java.util.Deque;
public class graph {
//private Deque<Integer>[] graphRepDeques;
final static int Amount = 200;
private Deque<Integer>[] s = new Deque[Amount];
public graph(String filename) {
In in = new In(filename);
//final int Amount = 200;
s = new Deque[Amount];
for (int i = 0; i < Amount; i++) {
String[] currentLine = in.readLine().split("\\s");
int size = currentLine.length;
s[i] =new Deque<Integer>(); // why Cannot instantiate the type Deque<Integer>???????
for (int j = 1; j < size; j++) {
int temp = Integer.parseInt(currentLine[j]);
s[i].add(temp);
}
}
}
private void show() {
for (int i = 0; i < Amount; i++) {
for (int a: s[i]) {
//StdOut.print(a + " ");
}
}
}
public static void main(String[] args) {
graph a = new graph("kargerMinCut.txt"); //whatever text you like with integers
a.show();
}
}
The error I got is
Cannot instantiate the type Deque<Integer>
I can instantiate Deque in the main function in class "Deque", but why I cannot do it in class "graph"? Very confused here
I appreciate any help thanks.
The goal of my code is to read the numbers
in a file line by line and for each line,
I store the numbers I got into a object of class Deque.
Therefore, I need an array of objects
of Deque to store all the numbers.
Similary to an array of linkedlist (Deque in my code).
The problem is I do not know how to initialized an array of this linkedlist (Deque in my code) properly so I can "push" all the keys in each linkedlist (Deque)
Since you applied Codebender's hint, you now just have to replace
s[i] = new Deque<Integer>();
with:
s[i] = new LinkedList<Integer>();
as you already mentioned in your question.
java.util.Deque is only an interface and therefore cannot be instantiated directly. All your variables (including the array) can still be of the type Deque and Deque[] respectively, since java.util.LinkedList implements that interface.
In your edited code, the problem is that you are just initializing the array. Not the Deque objects.
Deque<Integer>[] s = new Deque[10];
The above just creates an Array of 10 elements (and initializes all of them to null).
Hence s[0] is null, just like any other index. And you are trying to call addFirst(1) on null element.
So you should be initalizing each element in the array before using them,
s[i] = new Deque(); // In a loop if needed.
Related
interface Iterator {
boolean hasnext();
int next();
}
class practice5 {
public static void main(String a[]) {
Stack s = new Stack();
Queue q = new Queue();
Linkedlist l = new Linkedlist();
s.push(100);
s.push(200);
q.Enque(300);
q.Enque(400);
l.add(500);
l.add(600);
Iterator itr;
itr = s;
while (!itr.hasnext()) {
System.out.println(itr.next());
}
itr = q;
while (!itr.hasnext()) {
System.out.println(itr.next());
}
itr = l;
while (itr.hasnext()) {
System.out.println(itr.next());
}
}
}
class Stack extends Iterator {
private int stack[];
private int top;
public Stack() {
stack = new int[10];
top = -1;
}
public void push(int val) {
top++;
stack[top] = val;
}
public boolean hasnext() {
if (top >= 0) {
return false;
} else {
return true;
}
}
public int next() {
return (stack[top--]);
}
}
class Queue extends Iterator {
private int queue[];
private int front, rear;
public Queue() {
queue = new int[10];
front = 0;
rear = 0;
}
public void Enque(int val) {
queue[rear] = val;
rear++;
}
public boolean hasnext() {
if (front < rear) {
return false;
} else {
return true;
}
}
public int next() {
return (queue[front++]);
}
}
class Linkedlist extends Iterator {
private int data;
private Linkedlist nw, next, prev, first, guest;
public Linkedlist() {
nw = next = prev = first = null;
}
public void add(int val) {
nw = new Linkedlist();
nw.data = val;
if (first == null) {
prev = first = nw;
} else {
prev.next = nw;
prev = nw;
}
}
public boolean hasnext() {
if (guest != 0) {
return true;
} else {
return false;
}
}
public int next() {
int curval;
curval = first.data;
first = first.next;
return (curval);
}
}
I'm expecting that I get an output for the above code.
I need to know if I'm extending the Stack, Queue and LinkedList classes wrongly with the interface class. Whenever I'm pass the iterator class object the instance of my child class objects, I am getting an error.
Also, in the LinkedList section when I call guest != 0, I'm getting an error Bad Operand. How can I check and print whether my guest is equal to zero or not?
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 am attempting to create a singly linked list where I can add nodes that will have an integer value and a next value. I need to be able to traverse this list so I can add the elements of the list. Everything needs to be within one file. I am new to java and could use some assistance. Here is my code:
package LargestSum;
import java.io.*;
import java.util.Scanner;
public class LargestSum {
public static class LinkedList {
private int num;
private LinkedList node;
private LinkedList head;
private LinkedList tail;
private int listSize;
public LinkedList next;
public LinkedList(){
node = null;
num = 0;
head = null;
tail = null;
listSize = 0;
}
public void setLink(LinkedList l){
node = l;
}
public void setNum(int n){
num = n;
}
public LinkedList getNode(){
return node;
}
public int getNum(){
return num;
}
public boolean empty(){
return head == null;
}
public int getListSize(){
return listSize;
}
public void insert(int set){
LinkedList list = new LinkedList();
listSize++;
if(head == null){
head = list;
tail = head;
}
else {
tail.setLink(list);
tail = list;
}
}
}
public static void main(String[] args) throws IOException {
String fileName = "in.txt";
LinkedList list = new LinkedList();
Scanner numbers = new Scanner(new File(fileName));
while(numbers.hasNext()){
int num = numbers.nextInt();
list.insert(num);
System.out.println(num);
}
int listSize = list.getListSize();
}
}
I'd appreciate any type of help and pointers, please. Thank you.
Problem in your code is you are initializing linkedlist every time you add an element. so every node are not linked with each other. what you can do is make two classes: 1) node and 2) LinkedList
node will act has container element which denote element in LinkedList. LinkedList class will have all the functionality which you want to do.
I have made changes in your code instead pasting whole new code. so that you can understand difference between them by comparing your code with it.
//package LargestSum;
import java.io.*;
import java.util.Scanner;
public class Test {
public static class node{
int num;
node next;
public node(int num){
this.num = num;
next = null;
}
public node getNext(){
return next;
}
public void setNext(node t){
this.next = t;
}
public int getNum(){
return this.num;
}
}
public static class LinkedList {
//private int num;
//private LinkedList node;
private node head;
private node tail;
private int listSize;
//public LinkedList next;
public LinkedList(){
// node = null;
// num = 0;
head = null;
tail = null;
listSize = 0;
}
//public void setLink(LinkedList l){
// node = l;
//}
//public void setNum(int n){
// num = n;
//}
//public LinkedList getNode(){
// return node;
//}
//public int getNum(){
// return num;
//}
public boolean empty(){
return head == null;
}
public int getListSize(){
return listSize;
}
public void print(){
node traverse = head;
while(traverse!=null){
System.out.println(traverse.getNum());
traverse = traverse.getNext();
}
}
public void insert(int set){
// LinkedList list = new LinkedList();
node temp = new node(set);
listSize++;
if(head == null){
head = temp;
tail = temp;
}
else {
tail.setNext(temp);
tail = tail.getNext();
}
}
}
public static void main(String[] args) throws IOException {
// String fileName = "in.txt";
LinkedList list = new LinkedList();
Scanner numbers = new Scanner(System.in);
int x=10;
while(x >0){
int num = numbers.nextInt();
list.insert(num);
System.out.println("++++++++++++++++++++++++++++++++++++++++++++");
list.print();
x--;
}
System.out.println("++++++++++++++++++++++++++++++++++++++++++++");
list.print();
int listSize = list.getListSize();
}
}
Here, I have implemented very basic one. you can't add other functionality in this code directly. if you want to add other one just use this type of two classes as I used here and add functions in LinkedList class.
If you have any further query comment me.
Thanks,
Bhavik
I created my own linked list, but when I tried to run it there is an error:
Exception in thread "main" java.lang.NullPointerException
at List.add(List.java:8) //if(t.val ==null)
at main.main(main.java:38) //linput.add(inputLine.split(" ")[i]);
Here is my List class:
class List{
String val;
List next=null;
private List t;
public void add(String word){
if(t.val ==null)
t.val=word;
else while(!t.next.val.equals(null))
{
t=t.next;
if(t.next.val.equals(null))
{
t.next.val=word;
break;
}
}
}
public int get(String word)
{
int i=0;
if(t.val.equals(word))
i=0;
else while(!t.next.val.equals(word))
{
t=t.next;
i++;
if(t.next.val.equals(word))
{
i++;
}
}
return i;
}
public String indexOf(int i)
{
int counter=0;
while(counter<i)
{
t=t.next;
counter++;
}
return t.val;
}
}
And here is my main function :
static public void main(String[] args)
{
List linput = new List();
String inputLine = "Hey look at me.";
for(int i = 0 ; i < inputLine.split(" ").length ; i++)
{
linput.add(inputLine.split(" ")[i]);
}
System.out.println(linput.indexOf(0)+" "+linput.indexOf(1)+" "+linput.indexOf(2));
}
I initialized t but next time there is an error like this:
private List t =new List();
Exception in thread "main" java.lang.StackOverflowError
at List.<init>(List.java:5)
at List.<init>(List.java:5)
at List.<init>(List.java:5)
Sorry. I can't give my full code, because the rest of my code is working well (reading from txt etc....).
The error seems to be related to the variable 't' (i.e., private List t).
Did you initialize this variable ? The if (t.val == null) seems to be cribbing this as t is null (uninitialized) at this point
You should have allocated object (using new) for this variable.
Can you share the full code for the constructor of List ?
Assuming you want to implement a simple forward list, rather than use the Java LinkedList class, you need to:
Change your implementation of the list to reference nodes in the list
handle traversal of the linked nodes in your word list
Here is an example:
WordList class
package com.example.words;
class WordList {
private WordNode head = null;
private int listSize = 0;
public void add(String word) {
// TODO add check for duplicate word
if (head == null) {
head = new WordNode();
head.setValue(word);
listSize++;
} else {
WordNode current = head;
while (current.getNext() != null) {
current = current.getNext();
}
WordNode newNode = new WordNode();
newNode.setValue(word);
current.setNext(newNode);
listSize++;
}
}
public int getWordIndex(String word) {
WordNode current = head;
int index = 0;
boolean found = false;
while (!found && current != null) {
found = current.getValue().equalsIgnoreCase(word);
if (!found) {
index++;
current = current.getNext();
}
}
if (found) {
return index;
} else {
return -1;
}
}
public String indexOf(int i) {
int index = 0;
WordNode current = head;
if (i <= listSize) {
while (index < i) {
current = current.getNext();
index++;
}
return current.getValue();
} else {
return null;
}
}
public int size() {
return listSize;
}
}
WordNode Class
package com.example.words;
public class WordNode {
private String value;
private WordNode next = null;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public WordNode getNext() {
return next;
}
public void setNext(WordNode link) {
next = link;
}
}
Test Driver
package com.example.words;
public class Test {
public static void main(String[] args) {
//TODO handle punctuation
WordList myList = new WordList();
String inputLine = "Hey look at me.";
String[] pieces = inputLine.split(" ");
for (int i=0; i < pieces.length; i++) {
myList.add(pieces[i]);
}
for (int i=0; i < pieces.length; i++) {
String value = myList.indexOf(i);
if (value.equalsIgnoreCase(pieces[i])) {
System.out.println("Following node is wrong:");
}
System.out.println ("node " + i + ". = " + value);
}
}
}
You tried to create t as a member variable of its own class like this:
class List {
[...]
private List t = new List();
[...]
}
This won't work because the constructor of List would be called indefinitely.
Try lazy instantiation of t instead. Replace all access of t with a getter:
private List getT() {
if (this.t == null) {
this.t = new List();
}
return t;
}
I am trying to implement a Deque in java using linked list. As a start I want to implement the method addFirst(). Here is the problem I am getting -- when I add few Strings, for example, "one", "two" and "three", it is inserting correctly, but when iterating the deque, it is only giving the last added object, not all the objects. Is there anything I am missing?
public class Deque<Item> implements Iterable<Item> {
private Node first;
private Node last;
private int N;
public Iterator<Item> iterator() { return new DequeIterator(); }
private class Node {
private Item item;
private Node next;
}
public Deque() {
first = null;
last = null;
N = 0;
}
public boolean isEmpty() { return first == null || last == null; }
public int size() { return N; }
public void addFirst(Item item) {
if (null == item) { throw new NullPointerException("Can not add a null value"); }
Node oldFirst = first;
first = new Node();
first.item = item;
first.next = null;
if (isEmpty()) {
last = first;
} else {
oldFirst.next = first;
}
N++;
}
private class DequeIterator implements Iterator<Item> {
private Node current = first;
public boolean hasNext() { return current != null; }
public void remove() { throw new UnsupportedOperationException(); }
public Item next() {
if (!hasNext()) { throw new NoSuchElementException(); }
Item item = current.item;
current = current.next;
return item;
}
}
public static void main(String args[]) {
Deque<String> deque = new Deque<String>();
deque.addFirst("one");
deque.addFirst("two");
deque.addFirst("three");
deque.addFirst("four");
for (String s : deque) {
System.out.println(s); // prints only "four"
}
}
}
Change oldFirst.next = first to first.next = oldFirst in addFirst() and it should work.
Right now first.next after addFirst() call isn't pointing to anything, as you're setting it to null. This causes the hasNext() method to return false, resulting in invalid iteration.
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Deque<Item> implements Iterable<Item> {
private Deque.Node first;
private Deque.Node last;
private int N;
public Iterator<Item> iterator() {
return new Deque.DequeIterator();
}
private class Node {
private Item item;
private Deque.Node next;
}
public Deque() {
first = null;
last = null;
N = 0;
}
public boolean isEmpty() {
return first == null || last == null;
}
public int size() {
return N;
}
public void addFirst(Item item) {
if (null == item) {
throw new NullPointerException("Can not add a null value");
}
if (first == null && last == null) {
first = new Node();
first.item = item;
first.next = null;
last = first;
} else {
Node node = new Node();
node.item = item;
node.next = first;
first = node;
}
N++;
}
private class DequeIterator implements Iterator<Item> {
private Deque.Node current = first;
public boolean hasNext() {
return current != null;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Item item = (Item) current.item;
current = current.next;
return item;
}
}
public static void main(String args[]) {
Deque<String> deque = new Deque<String>();
deque.addFirst("one");
deque.addFirst("two");
deque.addFirst("three");
deque.addFirst("four");
for (String s : deque) {
System.out.println(s); // prints only "four"
}
}
}
output :
four
three
two
one