137 lines
2.8 KiB
Java
137 lines
2.8 KiB
Java
package com.hithomelabs.princeton1.module4;
|
|
|
|
|
|
import java.util.Iterator;
|
|
|
|
public class Deque<Item> implements Iterable<Item> {
|
|
|
|
private Node head;
|
|
private Node tail;
|
|
private int capacity;
|
|
|
|
private class Node{
|
|
Item value;
|
|
Node next;
|
|
}
|
|
|
|
public Deque(){
|
|
this.head = null;
|
|
this.tail = null;
|
|
this.capacity = 0;
|
|
}
|
|
|
|
public boolean isEmpty(){
|
|
return this.capacity == 0;
|
|
}
|
|
|
|
public int size(){
|
|
return this.capacity;
|
|
}
|
|
|
|
|
|
public void addFirst(Item item){
|
|
Node temp=this.head;
|
|
this.head=new Node();
|
|
this.head.value = item;
|
|
this.head.next = temp;
|
|
// System.out.println(this.isEmpty());
|
|
if(this.isEmpty())
|
|
this.tail=this.head;
|
|
this.capacity++;
|
|
}
|
|
|
|
public void addLast(Item item){
|
|
Node temp = new Node();
|
|
temp.value = item;
|
|
System.out.println(this.isEmpty());
|
|
if(!this.isEmpty()) {
|
|
this.tail.next = temp;
|
|
this.tail = this.tail.next;
|
|
}
|
|
else{
|
|
this.head = temp;
|
|
this.tail = temp;
|
|
}
|
|
this.capacity++;
|
|
}
|
|
|
|
public Item removeFirst(){
|
|
Item item = this.head.value;
|
|
this.head=this.head.next;
|
|
this.capacity--;
|
|
return item;
|
|
}
|
|
|
|
public Item removeLast(){
|
|
Item item = this.tail.value;
|
|
Node temp = this.head;
|
|
|
|
if(capacity <= 1){
|
|
this.tail=null;
|
|
this.head=null;
|
|
return item;
|
|
}
|
|
|
|
|
|
while(temp.next.next != null){
|
|
temp=temp.next;
|
|
}
|
|
|
|
this.tail=temp;
|
|
this.tail.next=null;
|
|
this.capacity--;
|
|
return item;
|
|
}
|
|
|
|
@Override
|
|
public Iterator<Item> iterator() {
|
|
|
|
return new Iterator<Item>() {
|
|
private Node current=head;
|
|
@Override
|
|
public boolean hasNext() {
|
|
return this.current != null;
|
|
}
|
|
|
|
@Override
|
|
public Item next() {
|
|
Item item = this.current.value;
|
|
this.current=this.current.next;
|
|
return item;
|
|
}
|
|
};
|
|
}
|
|
|
|
public static void main(String[] args){
|
|
Deque<String> deque = new Deque<String>();
|
|
|
|
deque.addLast("qwe");
|
|
deque.addFirst("asd");
|
|
deque.addLast("zxc");
|
|
|
|
for(String s: deque){
|
|
System.out.println(s);
|
|
}
|
|
|
|
deque.addLast("qwess");
|
|
|
|
System.out.println();
|
|
|
|
for(String s: deque){
|
|
System.out.println(s);
|
|
}
|
|
|
|
deque.removeFirst();
|
|
deque.removeLast();
|
|
deque.removeFirst();
|
|
deque.removeLast();
|
|
|
|
System.out.println();
|
|
|
|
for(String s: deque){
|
|
System.out.println(s);
|
|
}
|
|
|
|
}
|
|
}
|