public class StackLinked {
StackNode top;
int size;
int size() {
return size;
}
boolean isEmpty() {
return top == null;
}
void push(int data) {
if (top == null) {
top = new StackNode(data, null);
size++;
return;
}
top = new StackNode(data, top);
size++;
}
int pop() {
if (top == null) {
throw new EmptyStackException();
}
int data = top.data;
top = top.next;
size--;
return data;
}
int peek() {
if (top == null) {
throw new EmptyStackException();
}
return top.data;
}
public static void main(String[] args) {
StackLinked s=new StackLinked();
s.push(1);
s.push(2);
s.push(3);
System.out.println("size->"+s.size());
System.out.println("s.pop->"+s.pop());
System.out.println("s.pop->"+s.pop());
s.push(4);
System.out.println("s.pop->"+s.pop());
System.out.println("s.isEmpty->"+s.isEmpty());
System.out.println("s.peek->"+s.peek());
System.out.println("s.pop->"+s.pop());
System.out.println("s.isEmpty->"+s.isEmpty());
}
}
class StackNode {
int data;
StackNode next;
StackNode(int data, StackNode stackNode) {
this.data = data;
this.next = stackNode;
}
}
版权归属:
胖头鱼
许可协议:
本文使用《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》协议授权
评论区