栈、队列(链表实现)

package com.company;

import java.util.Iterator;

/**
 * Created by bbw on 2017/7/13.
 * 下压堆栈,链表实现
 * 实现长度、pop、push、非空
 */
public class Stack implements Iterable {

    private Node first;
    private int length;
    private class Node{
        Item item;
        Node next;
    }

    public boolean isEmpty(){
        //非空
        return length == 0;
    }

    public void push(Item item){
        //加入
        Node oldFirst = first;
        first = new Node();
        first.item = item;
        first.next = oldFirst;
        length++;
    }

    public Item pop(){
        //删除
        Item item = first.item;
        first = first.next;
        if (isEmpty())
            first = null;
        length--;
        return item;
    }


    @Override
    public Iterator iterator() {

        return new ListIterator() ;
    }
    private class ListIterator implements Iterator{

        private Node current = first;

        public boolean hasNext() {
            return current != null;
        }

        public Item next() {

            Item item = (Item) current.item;
            current = current.next;
            return item;
        }

        public void remove() {

        }
    }
}

package com.company;

import java.util.Iterator;

/**
 * Created by bbw on 2017/7/13.
 * 队列实现
 * 实现长度、非空、添加、删除
 */
public class Queue implements Iterable{


    private Node first;
    private Node last;
    private int length = 0;

    private class Node{
        Item item;
        Node next;
    }

    public boolean isEmpty(){
        return length ==0;
    }

    public void enQueue(Item item){
        //添加
        Node oldLast = last;
        last = new Node();
        last.item = item;
        last.next = null;
        if (isEmpty())
            last = first;
        else
            oldLast.next = last;
        length++;
    }

    public Item deQueue(){
        //删除
        Item item = first.item;
        first = first.next;
        if (isEmpty()){
            last = null;
        }
        length--;
        return item;

    }
    @Override
    public Iterator iterator() {

        return new ListIterator() ;
    }
    private class ListIterator implements Iterator{

        private Node current = first;

        public boolean hasNext() {
            return current != null;
        }

        public Item next() {

            Item item = (Item) current.item;
            current = current.next;
            return item;
        }

        public void remove() {

        }
    }
}


值得注意next方法会返回当前节点的item 并移向下一节点。

你可能感兴趣的:(栈、队列(链表实现))