addFirst() method in Deque implementation - java

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

Related

How to extend child classes with a parent interface class

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?

Java Deque Implementation Cannot convert Item

Deque implementation
I implemented a generic Deque data structure.
Please, review this implementation
and The error doesnt make sense to me, plz info me a little bit
import java.util.NoSuchElementException;
import java.util.Iterator;
public class Deque<Item> implements Iterable<Item>
{
private int n;
private Node first;
private Node last;
private class Node
{
private Item item;
private Node next;
}
private class ListIterator implements Iterable<Item>
{
private Node<Item> current = first;
public boolean hasNext()
{
return current != null;
}
public Item next()
{
if(!hasNext())
{
throw new NoSuchElementException("Deque underflow");
}
Item item = current.item;
current = current.next;
return item;
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
public Iterator<Item> iterator()
{
return new ListIterator();
}
public Deque()
{
n = 0;
first = null;
last = null;
}
// is the deque empty?
public boolean isEmpty()
{
return n ==0;
}
// return the number of items on the deque
public int size()
{
return n ;
}
// add the item to the front
public void addFirst(Item item)
{
if(item == null)
{
throw new IllegalArgumentException();
}
Node oldNode = first;
Node newNode = new Node();
newNode.item = item;
if(oldNode == null)
{
last = newNode;
}
else
{
newNode.next = oldNode;
}
first = newNode;
n++;
}
// add the item to the back
public void addLast(Item item)
{
if(item == null)
{
throw new IllegalArgumentException();
}
Node oldNode = last;
Node newNode = new Node();
newNode.item = item;
if(oldNode == null)
{
first = newNode;
}
else
{
oldNode.next = newNode;
}
last = newNode;
n++;
}
// remove and return the item from the front
public Item removeFirst()
{
if(isEmpty())
{
throw new NoSuchElementException("Deque underflow");
}
Item item = first.item;
first = first.next;
n--;
if(isEmpty())
{
first=null;
}
return item;
}
// remove and return the item from the back
public Item removeLast()
{
if(isEmpty())
{
throw new NoSuchElementException("Deque underflow");
}
Node secondLast = first;
if(n>3)
{
while(secondLast.next.next != null)
{
secondLast = secondLast.next;
}
}
else
{
secondLast = first;
}
Item item = last.item;
last = secondLast;
n--;
if(isEmpty())
{
last = null;
}
return item;
}
}
Test file
import java.util.Iterator;
public class dequeTest
{
public static void main(String[] args)
{
Deque<Double> d = new Deque<Double>();
System.out.println("Empty? "+d.isEmpty()+" \tSize is "+ d.size());
d.addFirst(2.0);
System.out.println(d.removeFirst());
System.out.println("Empty? "+d.isEmpty()+" \tSize is "+ d.size());
d.addFirst(1.2);
System.out.println(d.removeLast());
System.out.println("Empty? "+d.isEmpty()+" \tSize is "+ d.size());
d.addLast(1.4);
System.out.println("Empty? "+d.isEmpty()+" \tSize is "+ d.size());
for(int i = 0;i<10;i++)
{
d.addLast((double)i);
}
for(double value: d)
{
System.out.print(value);
}
}
}
Error
Type mismatch: cannot convert from Deque.ListIterator to Iterator
Can anyone help with the error? and fix it if you have a better idea
An Iterable<T> is not an Iterator<T>, but it has a method to get an Iterator<T>. Just change
public Iterator<Item> iterator()
{
return new ListIterator();
}
to
public Iterator<Item> iterator()
{
return new ListIterator().iterator();
}
beyond that, I would suggest you use an ArrayDeque (or even LinkedList) when you need a Deque. Your implementation does not appear to improve on either and worse your class name shadows the java.util.Deque interface (which you don't implement). Finally, a Deque should be a Collection (not just Iterable).

java linked list compare with first element and remove using peek() method

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;
}

Joining two self-written doubly-LinkedLists in Java constructor

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.

LinkedList - delete(Object) method works strange - deleting last element doesn't work properly

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.

Categories

Resources