`
iluoxuan
  • 浏览: 571062 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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

 

   

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics