?? stacksequence.java
字號(hào):
import java.io.*;
class StackNode{
int stackData = 0;
StackNode prev = null;
StackNode next = null;
StackNode(int input) {stackData = input;}
}
class IntStack{
StackNode tail = new StackNode(0);
int length = 0;
boolean isEmpty(){
if (length == 0)
return true;
else
return false;
}
void push(int input){
StackNode create = new StackNode(input);
create.next = null;
create.prev = tail;
tail.next = create;
tail = create;
length++;
}
int pop(){
int data = tail.stackData;
tail.prev.next = null;
tail = tail.prev;
length--;
return data;
}
int top(){
return tail.stackData;
}
}
public class StackSequence{
public static boolean judgeSequence(int[] sequence){
int[] workshop = new int[sequence.length];
int amount = sequence.length;
for (int i=0; i<amount; i++)
workshop[i] = i+1;
IntStack iStack = new IntStack();
for (int i=0; i<sequence.length; i++){
int target = sequence[i];
if (iStack.isEmpty()){
int pos = find(target, workshop, amount); //pos must be greater than -1
for (int j=0; j<pos; j++)
iStack.push(workshop[j]);
for (int j=0; j<amount-pos-1; j++)
workshop[j] = workshop[j+pos+1];
amount -= (pos+1);
}
else{//iStack is not empty
int topData = iStack.top();
if (target == topData){
iStack.pop();
continue;
}
else{ // topData != iStack.top();
int pos = find(target, workshop, amount);
if (pos == -1) return false;
for (int j=0; j<pos; j++)
iStack.push(workshop[j]);
for (int j=0; j<amount-pos-1; j++)
workshop[j] = workshop[j+pos+1];
amount -= (pos+1);
}
}
}
return true;
}
public static int find(int target, int[] array, int amount){
int pos = -1;
for (int i=0; i<amount; i++){
if (array[i] == target){
pos = i;
break;
}
}
return pos;
}
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = "";
while(true){
System.out.println("請(qǐng)輸入一個(gè)待判斷的輸出序列:");
line = br.readLine();
if (line.equals("finish"))
return;
String[] numbers = line.split(" ");
int[] sequence = new int[numbers.length];
for (int i=0; i<numbers.length; i++){
sequence[i] = Integer.parseInt(numbers[i]);
}
boolean result = judgeSequence(sequence);
if (result)
System.out.println("你給出的是合法輸出序列");
else
System.out.println("你給出的是非法輸出序列");
System.out.println();
}
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -