自己实现queue、stack

1、用数组实现的stack,包括动态调整大小,可迭代,泛型

import java.util.*;

public class arraystack<item> implements Iterable<item> {
    private item[] stack = (item[])new Object[1];
    private int sizes=0;
    private void resize(int len)
    {
        item[] new_stack=(item[])new Object[len];
        for(int i=0;i<sizes;i++)
        {
            new_stack[i]=stack[i];
        }
            stack=new_stack;

    }
    public int size(){
        return sizes;
    }
    public boolean isEmpty()
    {
        return sizes==0;
    }
    public void push(item data)
    {
        if(sizes==stack.length)
        {

            resize(sizes*2);
        }
        stack[sizes++]=data;            
    }
    public item pop()
    {
        item a=stack[--sizes];
        stack[sizes]=null;
        if(sizes>0 && sizes==stack.length/4)
            resize(stack.length/2);
        return a;
    }
    public Iterator<item> iterator()
    {
        return new stackIterator();
    }
    private class stackIterator implements Iterator<item>
    {
        private int count=sizes;
        public boolean hasNext()
        {
            return count>0;
        }
        public item next()
        {
            return stack[--count];
        }
        public void remove(){

        }
    }
}

2、链表实现stack

public class myStack<item> {
    private int len;
    private Node top;

    public boolean isEmpty()
    {
        return len==0;
    }
    public int size()
    {
        return len;
    }
    public void push(item data)
    {
        Node old_top=top;
        top=new Node();
        top.data=data;
        top.next=old_top;
        len++;

    }
    public item pop()
    {
        item head_data=top.data;
        top=top.next;
        len--;
        return head_data;
    }
     private class Node
        {
            item data;
            Node next=null; 
        }
}

3、链表实现队列

public class myQueue<item> {
    private int len;
    Node head;
    Node tail;
    public boolean isEmpty()
    {
        return len==0;
    }
    public int size()
    {
        return len;
    }
    public void enQueue(item data)
    {
        Node old_tail=tail;
        tail=new Node();
        tail.data=data;
        tail.next=null;
        if(isEmpty())
        {
            head=tail;
        }
        else
        {
           old_tail.next=tail;
        }
        len++;

    }
    public item deQueue()
    {
        item data=head.data;
        head=head.next;
        if(isEmpty())
            tail=null;
        len--;
        return data;

    }
     private class Node
        {
            item data;
            Node next=null; 
        }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值