1. 程式人生 > >棧(Stack)、佇列(Queue)與包(Bag)的實現

棧(Stack)、佇列(Queue)與包(Bag)的實現

使用基本的連結串列結構實現棧,佇列和包三種資料結構。首先用一個巢狀類來定義結點的抽象資料型別:

private class Node{
    Item item;
    Node next;
}

(1)堆疊Stack

import java.util.Iterator;
public class Stack<Item> implements Iterable<Item>{
    private Node first;//棧頂
    private int N;//元素數量
    private class Node{
        Item item;
        Node next;
    }
    public
void push(Item item){ Node oldfirst = first; first = new Node(); first.item = item; first.next = oldfirst; N++; } public Item pop(){ Item item = first.item; first = first.next; N--; return item; } //實現迭代 public
Iterator<Item> iterator(){ return new ListIterator(); } private class ListIterator implements Iterator<Item>{ private Node current = first; public boolean hasNext(){ return current != null; } public void remove(){} public
Item next(){ Item item = current.item; current = current.next;; return item; } } }

(2)佇列(Queue)的實現

public class Queue<Item> implements Iterator<Item>{
    private Node first;
    private Node last;
    private int N;
    private class Node{
        Item item;
        Node next;
    }
//佇列向隊尾填加元素
    public void enqueue(Item item){
        Node oldlast = last;
        last = new Node();
        last.item = item;
        last.next = null;
        if(isEmpty) first = last;
        else oldlast.next = last;
        N++;
        return item;    
    }
    public Item dequeue(){
        Item item = first.item;
        first = first.next;
        if(isEmpty()) last = null;
        N--;
        return item;
    }    
}

(3)包(Bag)

public class Bag<Item>{
    private Node first;
    private int N;
    private class Node{
        Item item;
        Node next;
    }
    public void add(Item item){
        Node oldfirst = first;
        first = new Node();
        first.item = item;
        first.next = oldfiirst;
    }
}

順序儲存結構:陣列
優點:通過索引可以任意訪問元素
缺點:初始化時需要知道元素數量
鏈式儲存結構:連結串列
優點:使用的空間大小和元素數量成正比
缺點:需要通過引用訪問任意元素