I am learning linked list and wrote a sample code to understand the fundamentals. My code works, but is there another way to print out the list using a for loop without the while loop?
I cheated using the for loop I made, because I already knew the number of nodes in the list. Is there a different way of printing the list using a for loop?
public class FriendNode {
FriendNode next;
String name;
FriendNode(String name)
{
this.name = name;
this.next = null;
}
public FriendNode(String name, FriendNode n)
{
this.name = name;
this.next = n;
}
public FriendNode getNext()
{
return this.next;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
FriendNode g = new FriendNode("Bob");
FriendNode o = new FriendNode("Alice");
FriendNode k = new FriendNode("Tom");
FriendNode m = new FriendNode("Day");
g.next = o;
o.next = k;
k.next = m;
m.next = null;
FriendNode current=g;
while(current!=null)
{
System.out.println(current);
current = current.next;
}
for(int i =0; i<4;i++)
{
System.out.println(current);
current = current.next;
}
}
}
You can do it this way :
for (FriendNode current=g; current != null; current = current.next) {
System.out.println(current);
}
This is assuming that g is the first node, since that's how you initialized current when printing the list with the while loop.
It is essentially doing the same as the while loop, except that the initialization and increment are moved to the for expression, which make it more compact.
The for loop doesn't have to work purely with ints, nor does it have to be incremented or decremented. This is also valid:
for (FriendNode ii = g; ii != null; ii = ii.next)
{
System.out.println(ii);
}
The potential problem with both, though, is that you run the risk of an infinite loop - if you set m.next to g, both the while loop and the for loop will execute forever. If you needed to, you could guard against that by keeping a reference to the FriendNode (g) you've started with, and breaking out of the loop if i is g.
You can implement Iterable and use "the other kind" of for loop
for (Friend f : new FriendList(g)) {
System.out.println(f.name);
}
I've created a FriendList that uses the FriendNode. And stuck a Friend object inside the FriendNode rather than just a string. IMO that will allow you better extensiblity going forwards.
The implementation looks like this:
import FriendList.Friend;
public class FriendList implements Iterable<Friend> {
public static class Friend {
public Friend(String name) {
this.name = name;
}
String name;
}
public static class FriendNode {
FriendNode next;
Friend friend;
FriendNode(String name)
{
this.friend = new Friend(name);
this.next = null;
}
public FriendNode(String name, FriendNode n)
{
this.friend = new Friend(name);
this.next = n;
}
public FriendNode getNext()
{
return this.next;
}
}
public FriendList(FriendNode n) {
first = n;
}
#Override public Iterator<Friend> iterator() {
return new Iterator<Friend>() {
FriendNode node = first;
#Override public boolean hasNext() {
return node != null;
}
#Override public Friend next() {
Friend f = node.friend;
node = node.next;
return f;
}
#Override public void remove() {
throw new UnsupportedOperationException();
}
};
}
FriendNode first;
public static void main(String[] args) {
// TODO Auto-generated method stub
FriendNode g = new FriendNode("Bob");
FriendNode o = new FriendNode("Alice");
FriendNode k = new FriendNode("Tom");
FriendNode m = new FriendNode("Day");
g.next = o;
o.next = k;
k.next = m;
m.next = null;
FriendList list = new FriendList(g);
for (Friend f : list) {
System.out.println(f.name);
}
}
}
Related
I am new to the concept of Linked list, and I am having a lot of trouble building this custom linked list for the first time.
I have two classes: CellPhone and CellList.
In CellPhone, I have 4 attributes: serialNum(long), brand(String), year(int), and price(double).
In CellList, I have:
an inner class called CellNode, which has two attributes: phone(CellPhone), and next(CellNode)
and two attributes head(CellNode) and size(int)
This is from my CellList class:
private CellNode head; // point first node in this list object
private int size; // current size of the list(how many nodes in the list)
public CellList() {
head = null;
size = 0;
}
public CellList(CellList c) { // is this a correct deep copying?
head = new CellNode(c.head);
size = c.getSize();
}
public int getSize() {
return size;
}
public void addToStart(CellPhone c) {
head = new CellNode(c, null); //head.getPhone() = c, head.getNextNode() = null.
size++;
}
I am not even sure if that addToStart method is correctly done, and now I need to add methods like insertAt(/deleteFrom)Index(CellPhone c, int index). I've done till here:
public void insertAtIndex(CellPhone c, int index) { //index is invalid when it's not 0<index<size-1
if(index<0 || index>size-1) {
throw new NoSuchElementException("index is invalid! System terminated.");
}
but I can't fully understand how this Node thing works, so I am stuck.
Here is the full code:
import java.util.NoSuchElementException;
public class CellList {
class CellNode {
private CellPhone phone;
private CellNode next;
public CellNode() {
phone = null;
next = null;
}
public CellNode(CellPhone c, CellNode n) {
phone = c;
next = n;
}
public CellNode(CellNode c) {
this(c.getPhone(), c.getNextNode());
}
public CellNode clone() {
CellNode c = new CellNode(phone, next);
return c;
}
public CellPhone getPhone() {
return phone;
}
public CellNode getNextNode() {
return next;
}
public void setPhone(CellPhone c) {
phone = c;
}
public void setNextNode(CellNode n) {
next = n;
}
}
private CellNode head; // point first node in this list object
private int size; // current size of the list(how many nodes in list)
public CellList() {
head = null;
size = 0;
}
public CellList(CellList c) {
head = new CellNode(c.head);
size = c.getSize();
}
public int getSize() {
return size;
}
public void addToStart(CellPhone c) {
head = new CellNode(c, null); //head.getPhone() = c, head.getNextNode() = null.
size++;
}
public void insertAtIndex(CellPhone c, int index) { //index is invalid when it's not 0<index<size-1
if(index<0 || index>size-1) {
throw new NoSuchElementException("index is invalid! System terminated.");
}
}
public void showContents() {
while(head.getNextNode() != null) {
System.out.println(head.getPhone()+"---->");
head = head.getNextNode();
}
}
}
If you want to insert a node at an index x you have to,
go to the node at index x-1, store the next value of node x-1 in a temp variable, put the node you want to insert in next property of x-1 node, and put the value in the temp variable in the next property of the node you want to insert.
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 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.
I would like to create a third list by connecting 2 others. I tried to do it, but as I expected my idea was wrong and everything doesn't work fine. Below you can see List file and test program. The other (empty) constructors of List are meant to connect 2 lists by adding elements of one List before specific index of the second list, and adding elements of one List before specific element of the second one using equals() method. It will be also hard for me for sure, but I ask only for simply connecting elements to obtain something like that:
(L11, L12, L13)+(L21, L22, L23) = L11,L12,L13,L21,L22,L23
public class Lista implements List {
private Element head = new Element(null); //wartownik
private int size;
public Lista(){
clear();
}
public Lista(Lista lista1, Lista lista2) {
head.previous = lista2.head.previous;
head.next = lista1.head.next;
}
public Lista(Lista lista1, Lista lista2, int index) {
}
public Lista(Lista lista1, Lista2. Object value) {
}
public void clear(){
head.setPrevious(head);
head.setNext(head);
size=0;
}
public void insert(int index, Object value) throws IndexOutOfBoundsException {
if (index<0 || index>size) throw new IndexOutOfBoundsException();
Element element = new Element(value);
element.wstawPrzed(getElement(index));
++size;
}
public Element getElement(int index) {
Element szukany = head.getNext();
for (int i=index; i>0; --i)
szukany = szukany.getNext();
return szukany;
}
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 void infoOStanie() {
if (isEmpty()) {
System.out.println("Lista pusta.");
}
else
{
System.out.println("Lista zawiera " + size() + " elementow.");
}
}
public IteratorListowy iterator() {
return new IteratorListowy();
}
public void wyswietlListe() {
System.out.println();
IteratorListowy iterator = iterator();
for (iterator.first(); !iterator.isDone(); iterator.next())
{
System.out.println(iterator.current());
}
System.out.println();
}
private static final class Element{
private Object value;
private Element next; //Referencja do kolejnego obiektu
private Element previous; //Referencja do elementu poprzedniego
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;
}
public void setPrevious(Element previous) {
if (previous != null)
this.previous = previous;
}
public Element getPrevious() {
return previous;
}
public void wstawPrzed(Element next) {
Element previous = next.getPrevious();
setNext(next);
setPrevious(previous);
next.setPrevious(this);
previous.setNext(this);
}
public void delete() {
previous.setNext(next);
next.setPrevious(previous);
}
}
private class IteratorListowy implements Iterator{
private Element current;
public IteratorListowy() {
current = head;
}
public void next() {
current = current.next;
}
public void previous() {
current = current.previous;
}
public boolean isDone() {
return current == head;
}
public Object current() {
return current.value;
}
public void first() {
current = head.getNext();
}
public void last() {
current = head.getPrevious();
}
}
}
test
public class Program {
public static void main(String[] args) {
Lista lista1 = new Lista();
Lista lista2 = new Lista();
Lista lista3 = new Lista(lista1, lista2);
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("Całka", 14124);
Student s8 = new Student("Pabin", 1258);
Student s9 = new Student("Dryjas", 7896);
Student s10 = new Student("Zając", 5642);
lista1.insert(0, s1);
lista1.insert(0, s2);
lista1.insert(0, s3);
lista1.insert(0, s4);
lista1.insert(0, s5);
lista1.wyswietlListe();
lista1.infoOStanie();
lista2.insert(0, s6);
lista2.insert(0, s7);
lista2.insert(0, s8);
lista2.insert(0, s9);
lista2.insert(0, s10);
lista2.wyswietlListe();
lista2.infoOStanie();
lista3.wyswietlListe();
}
}
As I understood you are trying to concatenate two doubly linked lists list1 and list2, so you would need this simple logic :
// tail of list1 should point to head of list2
lista1.tail.next = lista2.head;
// as we are doubly linked, head of list2 should point back to tail of list1
lista2.head.previous = lista1.tail
this is it, the head of the list1 will now be the head of result list.
Now, doing it in your constructor :
public Lista(Lista lista1, Lista lista2) {
// get hold of lisa1.tail
Element lista1Tail = lista1.getElement(lista1.size() - 1);
listaTail.next = lista2.head;
//now pointer back to tail of lista1
lista2.head.previous = listaTail;
}
This will work, given you fix your getElement() method (which now return not correct index) and add null pointer checks for boundary cases.
As a simpler alternative, I recommend keeping tail member of your list, it is cleaner and more performant.