双方向リストによるスタック、キュー
スタックとして利用する際には、
DLList L = new DLList();
L.Push("A");
L.Push("B");
String s = L.Pop();
のように使います。Pop()のかわりにPopLast()を使えばキューになります。
import java.io.*;
public class DLList {
ListItem head = null;
ListItem tail = null;
/* constructor */
DLList() {}
boolean IsEmpty() { return (head == null); }
Object Head() { return head.inf(); }
Object Hail() { return tail.inf(); }
/* Methods for Stack operation */
public void Push(Object o)
{
ListItem r = new ListItem(o);
r.next = head;
if (head != null) head.prev = r;
if (tail == null) tail = r;
head = r;
}
public Object Pop()
{ if (head == null) return null;
Object ret = head.inf();
head = head.next;
if (head == null) tail = null;
return ret;
}
public Object PopLast()
{ if (tail == null) return null;
Object ret = tail.inf();
tail = tail.prev;
if (tail == null) head = null;
return ret;
}
/* Definition of list boxes */
class ListItem
{
Object obj;
ListItem (Object o) { obj = o; }
ListItem prev;
ListItem next;
public Object inf() { return obj; }
}
}