数据结构(二):栈Stack简介及其Java实现

栈是先进后出。其实现主要有两种,一种是基于链表的实现,一种是基于数组的实现。

基于链表的实现

import java.util.Iterator;
import java.util.NoSuchElementException;

/*
 * 基于单向链表实现的栈,先进后出
 */
public class Stack<Item> implements Iterable<Item> {

	
	private Node<Item> first; // top of stack
	private int n; // size of the stack

	// helper linked list class
	private static class Node<Item> {
		private Item item;
		private Node<Item> next;
	}

	/**
	 * Initializes an empty stack.
	 */
	public Stack() {
		first = null;
		n = 0;
	}
	
	public boolean isEmpty() {
		return first == null;
	}
	
	public int size() {
		return n;
	}

	public void push(Item item) {
		Node<Item> node = new Node<Item>();
		node.item = item;
		node.next = first;
		first = node;
		n++;
	}

	public Item pop() {
		if(this.isEmpty()) 
			throw new NoSuchElementException();
		Item item = first.item;
		first = first.next;
		n--;
		return item;
	}
	
	public Iterator<Item> iterator() {
		return new Iterator<Item>() {
			private Node<Item> current = first;

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

			public Item next() {
				if(!hasNext())
					throw new NoSuchElementException();
				Item item = current.item;
				current = current.next;
				return item;
			}
			
		};
	}
}

基于数组的实现

import java.util.Iterator;
import java.util.NoSuchElementException;

public class ArrayStack<Item> implements Iterable<Item> {

	private static final int DEFAULT_CAPACITY = 10;
	private Item[] items;
	private int n;

	public ArrayStack() {
		items = (Item[])new Object[DEFAULT_CAPACITY];
		n = 0;
	}
	
	public void push(Item item) {
		if(n == items.length)
			ensureCapacity(2*n + 1);
		items[n++] = item;
	}
	
	public Item pop () {
		if(isEmpty())
			throw new NoSuchElementException();
		Item item = items[--n];
		items[n] = null;
		if(n < items.length/4 && items.length/2 > DEFAULT_CAPACITY)
			ensureCapacity(items.length/2);
		return item;
	}
	
	public boolean isEmpty() {
		return n == 0;
	}
	
	public int size() {
		return n;
	}
	
	private void ensureCapacity(int nc) {
		if(nc < n)
			return;
		Item[] old = items;
		items = (Item[])new Object[nc];
		for(int i=0;i<n;i++) {
			items[i] = old[i];
		}
	}
	
	public Iterator<Item> iterator() {
		return new Iterator<Item>() {
			
			private int current = n;
			
			public boolean hasNext() {
				return n>0;
			}

			public Item next() {
				if(!hasNext())
					throw new NoSuchElementException();
				return items[--n];
			}
			
		};
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值