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
Related
I doesnt quite get why the part with the object names down there works? I invoke the method append(int number) with a parameter in my main method and create a List of Node Objects that store integer values this way. However, why wont the object names "temp" and "current" be replaced when a call append a second, a third.... time. They are always the same object names and one object name cant refer to multiple objects, I thought. When I call the method elementAt(), I get everytime the response I wanna have, but I dont know exactly why it did work.
Heres my Code for the Class MyList
public class MyList
{
Node head;
int count;
Node temp;
Node current;
public MyList(){
head= new Node(0);
count = 0;
}
public void append(int number){
temp = new Node(number);
current = head;
while(current.getNext() != null){
current = current.getNext();
}
current.setNext(temp);
count++;
}
public int elementAt(int number){
if(head != null){
current = head.getNext();
for(int i = 0; i < number ; i++){
if(current.getNext() == null){
return 0;
}
current = current.getNext();
}
return current.item;
}
return 0;
}
}
Heres the Code for the Class Node
public class Node {
public int item;
public Node next;
public Node(int item){
this.item = item;
}
public Node getNext(){
return next;
}
public void setNext(Node next){
this.next = next;
}
}
Heres the code for my the Main Class
public class MainList {
public static void main(String[] args) {
MyList list = new MyList();
list.append(10);
list.append(20);
list.append(30);
list.append(40);
list.append(50);
list.append(60);
list.append(40);
System.out.println(list.elementAt(0));
}
}
import org.w3c.dom.Node;
import java.util.ListIterator;
import java.util.NoSuchElementException;
public class LinkedList{
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.addFirst(2);
l.addFirst("c");
System.out.println(l);
}
private Node first;
private class Node {
public Object data;
public Node next;
}
public void addFirst(Object obj){
Node newNode = new Node();
newNode.data=obj;
newNode.next=first;
first=newNode;
}
}
It looks to me like you have implemented the addFirst method, but you need to implement a toString() method so that you can print out the contents of the list.
For example:
#Override
public String toString() {
String s = "";
Node n = first;
while (n != null) {
s += n.data + "\n";
n = n.next;
}
return s;
}
Prints:
c
2
public class LinkedList{
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.addFirst("c");
l.addFirst("7");
System.out.println(l);
}
private Node first;
static class Node {
String data;
Node next;
}
private void addFirst(String s){
Node newNode = new Node();
newNode.data=s;
newNode.next=first;
first= newNode;
}
}
// Is something wrong with addfirst method? Its still not working.
im trying to create a linked list but i keep getting that error, i am new to linked list and cant figure out whats happening. the code seems to work other lists that insert two data types into the node class.
EDIT: i am using netbeans and all 3 classes are in the same package, and they are the only
main class
public class assignment6 {
public static void main(String[] args) {
PQueue p = new PQueue();
p.push(22);
p.push(11);
p.push(2);
p.display();
/*
*/
}
}
linked list class
class PQueue {
public Node firstL;
PQueue(){
firstL = null;
}
public boolean isEmpty(){
return (firstL == null);
}
public void push(int num){
Node n = new Node(num);
n.next = firstL;
firstL = n;
}
public void display(){
Node link = firstL;
while(link != null){
link.display();
link=link.next;
}
}
}
node class
public class Node {
public int num;
public Node next;
public Node(int num){
this.num = num;
}
public void display(){
System.out.println(num);
}
}
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.
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
}}