Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Deque<Item> implements Iterable<Item> {
- private int size; // number of items
- private Node first; // top of stack
- private Node last;
- private class Node {
- Item item;
- Node next;
- Node previous;
- public Node(Item itemX) {
- item = itemX;
- }
- public Node() {
- }
- }
- public Deque() {
- first = null;
- last = null;
- size = 0;
- }
- public boolean isEmpty() {
- return first == null;
- }
- public int size() {
- return size;
- }
- public void pushRight(Item item) {
- //adds item to top of stack
- Node newNode = new Node(item);
- newNode.next = null;
- if (isEmpty()) {
- first = newNode;
- } else {
- last.next = newNode;
- newNode.previous = last;
- }
- last = newNode;
- }
- public void changeLeft(int k, Item newItem){
- int i = 1;
- Node current = first;
- while(i < k && current != null){
- current = current.next;
- i++;
- }
- if(current != null){
- current.item = newItem;
- }
- else{
- System.out.println("Linkedlist out of bounds");
- }
- }
- public void changeRight(int k, Item newItem){
- int size2 = size;
- Node current = last;
- while(size2 > k && current != null){
- current = current.previous;
- size--;
- }
- if(current != null){
- current.item = newItem;
- }
- else{
- System.out.println("Linkedlist out of bounds");
- }
- }
- public void pushLeft(Item item) {
- //adds item to bottom of stack
- Node newNode = new Node(item);
- if (isEmpty()) {
- last = newNode;
- } else {
- first.previous = newNode;
- }
- newNode.next = first;
- first = newNode;
- }
- public Item popLeft() {
- Item t = first.item;
- if (first.next == null) {
- last = null;
- } else {
- first.next.previous = null;
- }
- first = first.next;
- return t;
- }
- public Item popRight() {
- Item t = last.item;
- if (first.next == null) {
- first = null;
- } else {
- last.previous.next = null;
- }
- last = last.previous;
- return t;
- }
- public void printDeque() {
- Node tmpNode = first;
- while (tmpNode != null) {
- System.out.print(tmpNode.item + " -> ");
- tmpNode = tmpNode.next;
- }
- System.out.print("null");
- }
- @Override
- public Iterator<Item> iterator() {
- throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement