Personal tools
You are here: Home documents lectures Java Sample Programs 双方向リストによるスタック、キュー
Document Actions

双方向リストによるスタック、キュー

by member last modified 2007-03-21 11:45
スタックとして利用する際には、
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; }
}
}


Powered by Plone, the Open Source Content Management System

This site conforms to the following standards: