用顺序表实现栈(非扩容)
顺序栈
class Stack{
public int[] elem;
public int usedsize;
public Stack(){
this.elem=new int[5];
}
public boolean isFull(){
return this.usedsize==this.elem.length;
}
public boolean isEmpty(){
if(usedsize==0){
return true;
}
return false;
}
public void push(int val){
if(isFull()){
return;
}
this.elem[this.usedsize]=val;
this.usedsize++;
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈为空");
}
int ret=this.elem[usedsize-1];
this.usedsize--;
return ret;
}
public int peek(){
if(isEmpty()){
return -1;
}
return this.elem[usedsize-1];
}
}
public class TestDemo{
public static void main(String[] args) {
Stack stack=new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.pop());
System.out.println(stack.peek());
}
}
链式栈最好用头插法,头删法 空间复杂度和时间复杂度为O(1)
链式队列
class Node {
public Node next;
public int val;
public Node(int val) {
this.val = val;
}
}
class MyQueue {
public Node head;
public Node tail;
public void offer(int val) {
Node node = new Node(val);
if (this.head == null) { //第一次插入
this.head = node;
this.tail = node;
return;
}
this.tail.next = node;
this.tail = this.tail.next;
}
public int poll() {
if (this.head == null) {
throw new RuntimeException("队列为空!");
}
int data = this.head.val;
if (this.head.next == null) {
this.head = null;
this.tail = null;
} else {
this.head = this.head.next;
}
return data;
}
public int peek() {
if (this.head == null) {
throw new RuntimeException("栈为空!");
}
return this.head.val;
}
public boolean isEmpty(){
if(this.head==null){
return true;
}
return false;
}
}
public class TestDemo{
public static void main(String args[]){
MyQueue queue=new MyQueue();
queue.offer(1);
queue.offer(2);
queue.offer(3);
System.out.println(queue.poll());
System.out.println(queue.peek());
System.out.println(queue);
}
}
循环队列
底层是一个数组