1:Stack实现

1:先进后出栈的实现:

       

    才用头结点的方式:

 

    

package com.algorithm.common;

import java.util.Iterator;

/**
 * 链表实现先进后出的Stack
 * @author lijunqing
 */
public class Stack<Item> implements Iterable<Item> {

    private int N;

    private Node head;

    class Node {

        private Item item;

        private Node next;
    }

    public Stack() {
        N=0;
        head=new Node();
    }

    /**
     * 入栈
     * @param item head---first ---head.next
     */
    public void push(Item item) {
        Node first=new Node();
        first.item=item;
        first.next=head.next;
        head.next=first;
        N++;
    }

    /**
     * 出栈 head --- head.next.next
     * @return
     */
    public Item pop() {
        Node first=head.next;
        head.next=first.next;
        N--;
        return first.item;
    }

    public int size() {
        return N;
    }

    public boolean isEmpty() {
        if(N == 0) {
            return true;
        }
        return false;
    }

    @Override
    public Iterator<Item> iterator() {
        return new ListIterator();
    }

    private class ListIterator implements Iterator<Item> {

        private Node current=head.next;

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

        @Override
        public Item next() {
            Item item=current.item;
            current=current.next;
            return item;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }

    }

    public static void main(String[] args) {
        Stack<String> s=new Stack<String>();
        s.push("as");
        s.push("bs");
        s.push("eee");

//        System.out.println(s.size());
//        String a=s.pop();
//        String b=s.pop();
//        System.out.println(a + " 2 " + b);
//        System.out.println(s.isEmpty());

        Iterator<String> iterator=s.iterator();
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

}

 

   结果:

 

eee
bs
as

 

   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值