題目
Steque。一個以棧爲目標的的隊列(或稱steque),是一種支持push、pop和enqueue操作的數據類型。爲這種抽象數據類型定義一份API並給出一份居於鏈表的實現。
思路
思路很簡單,就是在用鏈表建立的棧中添加一個enqueue方法,使能在棧底添加數據。
代碼
package Chap1.$3;
import java.util.Scanner;
public class E32
{
private class Node
{
Node next;
int item;
}
private Node first;
private Node last;
private int N = 0;
public boolean isEmpty()
{
return N == 0;
}
public int size()
{
return N;
}
public void push(int item)
{
Node oldfirst = first;
first = new Node();
first.item = item;
if (isEmpty()) last = first;
else first.next = oldfirst;
N++;
}
public int pop()
{
int item = first.item;
first = first.next;
N--;
return item;
}
public void enqueue(int item)
{
Node oldlast = last;
last = new Node();
last.item = item;
if (isEmpty()) first = last;
else oldlast.next = last;
N++;
}
public int dequeue()
{
int item = last.item;
Node x = first;
for (int i = 0; i < this.size() - 2; i++)
x = x.next;
last = new Node();
last = x;
N--;
return item;
}
public void start()
{
E32 e = new E32();
Scanner in = new Scanner(System.in);
while (in.hasNext())
{
e.push(in.nextInt());
e.enqueue(in.nextInt());
}
int maxsize = e.size();
for (int i = 0; i < maxsize; i++)
{
System.out.print(e.pop() + " ");
System.out.print(e.dequeue() + " ");
i++;
}
}
public static void main(String[] args)
{
new E32().start();
}
}