- public static void main(String[] args)
- {
- Stack
s = new Stack(); - s.push(1);
- s.push(2);
- s.push(3);
- s.push(4);
- System.out.println(s.size()); // 获取栈中有效元素个数---> 4
- System.out.println(s.peek()); // 获取栈顶元素---> 4
- s.pop(); // 4出栈,栈中剩余1 2 3,栈顶元素为3
- System.out.println(s.pop()); // 3出栈,栈中剩余1 2 栈顶元素为3
- if(s.empty())
- {
- System.out.println("栈空");
- }
- else
- {
- System.out.println(s.size());
- }
- }
- public class MyStack
- {
- int[] array;
- int size;
- public MyStack()
- {
- array = new int[3];
- }
- public int push(int e)
- {
- ensureCapacity();
- array[size++] = e;
- return e;
- }
- public int pop()
- {
- int e = peek();
- size--;
- return e;
- }
- public int peek()
- {
- if(empty())
- {
- throw new RuntimeException("栈为空,无法获取栈顶元素");
- }
- return array[size-1];
- }
- public int size()
- {
- return size;
- }
- public boolean empty()
- {
- return 0 == size;
- }
- private void ensureCapacity()
- {
- if(size == array.length)
- {
- array = Arrays.copyOf(array, size*2);
- }
- }
- }
1. 若进栈序列为 1,2,3,4 ,进栈过程中可以出栈,则下列不可能的一个出栈序列是()A: 1,4,3,2 B: 2,3,4,1 C: 3,1,4,2 D: 3,4,2,12.一个栈的初始状态为空。现将元素 1 、 2 、 3 、 4 、 5 、 A 、 B 、 C 、 D 、 E依次入栈,然后再依次出栈,则元素出栈的顺序是( )。A: 12345ABCDE B: EDCBA54321 C: ABCDE12345 D: 54321EDCBA
- // 递归方式
- void printList(Node head)
- {
- if(null != head)
- {
- printList(head.next);
- System.out.print(head.val + " ");
- }
- }
-
- // 循环方式
- void printList(Node head)
- {
- if(null == head)
- {
- return;
- }
-
- Stack
s = new Stack<>(); - // 将链表中的结点保存在栈中
- Node cur = head;
- while(null != cur)
- {
- s.push(cur);
- cur = cur.next;
- }
-
- // 将栈中的元素出栈
- while(!s.empty())
- {
- System.out.print(s.pop().val + " ");
- }
- }
栈的压入、弹出序列_牛客题霸_牛客网 (nowcoder.com)
注意:Queue是个接口,在实例化时必须实例化LinkedList的对象,因为LinkedList实现了Queue接口。
- public static void main(String[] args)
- {
- Queue
q = new LinkedList<>(); - q.offer(1);
- q.offer(2);
- q.offer(3);
- q.offer(4);
- q.offer(5); // 从队尾入队列
- System.out.println(q.size());
- System.out.println(q.peek()); // 获取队头元素
-
- q.poll();
- System.out.println(q.poll()); // 从队头出队列,并将删除的元素返回
-
- if(q.isEmpty())
- {
- System.out.println("队列空");
- }
- else
- {
- System.out.println(q.size());
- }
- }
数组下标循环的小技巧
2. 下标最前再往前(offffset 小于 array.length): index = (index + array.length - offffset) % array.length
如何区分空与满
622. 设计循环队列 - 力扣(LeetCode)https://leetcode.cn/problems/design-circular-queue/
Deque是一个接口,使用时必须创建LinkedList的对象。