单向链表模拟栈
public class test8 {
public static void main(String[] args) {
SingleLinkStack singleLinkStack = new SingleLinkStack(6);
for (int i=0,j=0;i<6;i++,j+=2){
singleLinkStack.push(j);
}
}
}
class SingleLinkStack{
private int maxSize;
private SingleLink stack;
private int top = -1;
public SingleLinkStack(int maxSize) {
this.maxSize = maxSize;
stack = new SingleLink();
}
public boolean isFull(){
return top == maxSize-1;
}
public boolean isEmpty(){
return top == -1;
}
public void push(int value){
if (isFull()){
System.out.println("栈满");
return;
}
top++;
Node4 node = new Node4(value);
stack.add(node);
}
public int pop(){
if (isEmpty()){
throw new RuntimeException("栈空");
}
int value = stack.del();
top--;
return value;
}
public void list(){
if (isEmpty()){
System.out.println("栈空");
return;
}
stack.list();
}
}
class SingleLink {
private Node4 head = null;
public void add(Node4 node) {
if (head == null) {
head = node;
} else {
node.next = head;
head = node;
}
}
public int del(){
Node4 tmp = head;
Node4 cur = null;
while (true){
if (tmp.next.next == null){
break;
}
tmp = tmp.next;
}
cur = tmp.next;
tmp.next = null;
return cur.no;
}
public void list() {
Node4 tmp = head;
while (true) {
if (tmp == null) {
break;
}
System.out.println(tmp.no);
tmp = tmp.next;
}
}
}
class Node4{
public int no;
public Node4 next;
public Node4(int no) {
this.no = no;
}
}
|