用顺序表和链表分别实现栈和队列
一、栈的实现(入栈、出栈、取栈顶元素)
- 顺序表实现栈操作:
- 入栈——>顺序表尾插实现
- 出栈——>顺序表尾删实现
- 取栈顶元素——>根据下标获取元素
代码实现:
public class MyStack {
//用顺序表实现栈
private int[] data = new int[100];
private int size = 0;
//1.入栈
public void push(int val){
if(size >= data.length){
return ;
}
data[size] = val;
size++;
}
//2.出栈
public Integer pop(){
if(size == 0){
return null;
}
Integer result = data[size - 1];
size--;
return result;
}
//3.取栈顶元素
public Integer peek(){
if(size == 0){
return null;
}
return data[size - 1];
}
}
- 链表实现栈操作:
- 入栈——>链表头插实现
- 出栈——>链表头删实现
- 取栈顶元素——>链表取头节点的值
代码实现:
class ListNode{
int val;
ListNode next = null;
public ListNode(int val) {
this.val = val;
}
}
//用链表实现栈
public class MyStackByLinkedList {
//不带傀儡节点的链表
ListNode head = null;
//1.入栈(头插)
public void push(int val){
ListNode newNode = new ListNode(val);
if(head == null){
head = newNode;
return;
}
newNode.next = head;
head = newNode;
}
//2.出栈(头删)
public Integer pop(){
if(head == null){
return null;
}
if(head.next == null){
Integer ret = head.val;
head = null;
return ret;
}
int ret = head.val;
head = head.next;
return ret;
}
//3.取栈顶元素
public Integer peek(){
if(head == null){
return null;
}
return head.val;
}
}
二、队列的实现(入队列、出队列、取队首元素)
- 顺序表实现队列操作:利用环形队列实现
- 创建两个引用head,tail;
- 队列的有效元素区间 [head,tail) ;
- 入队列——> head 不动,tail 往后移动一步,即tail++;(每当 tail == 数组长度时,置 tail = 0,形成环形队列)
- 出队列——> tail 不动,head 往后移动一步,即head++ ;(每当 head == 数组长度时,置 head = 0,形成环形队列)
- 取队首元素——> 获取下标为head的元素。
环形队列为空时,head 和 tail 重合,环形队列为满时,head 和 tail 也重合。如何区分环形队列的空与满呢?有以下两种解决方法:
方法1:通过浪费一个空间来解决。head 和 tail 重合,则为空队列;tail = head - 1,则为满队列。
方法2:用 size 记录队列中元素个数。size == 0,则为空队列;size == 数组长度,则为满队列。
代码实现:(以下代码实现采用方法2)
public class MyQueueByArrayList {
//用顺序表实现队列
//有效区间 [head,tail) 循环队列
private int[] data = new int[100];
private int size = 0;
private int head = 0;
private int tail = 0;
//1.入队列
public boolean offer(int val){
if(size == data.length){
return false;
}
//将新元素放到tail下标上
data[tail] = val;
tail++;
//tail到达数组末尾后,置tail = 0;
if(tail == data.length){
tail = 0;
}
size++;
return true;
}
//2.出队列
public Integer poll(){
if(size == 0){
return null;
}
int ret = data[head];
head++;
if(head == data.length){
head = 0;
}
size--;
return ret;
}
//3.取队首元素
public Integer peek(){
if(size == 0){
return null;
}
return data[head];
}
}
- 链表实现队列操作:
- 入队列——>链表尾插实现
- 出队列——>链表头删实现
- 取队首元素——>链表获取头节点的值
代码实现:
class Node{
int val;
Node next = null;
public Node(int val) {
this.val = val;
}
}
public class MyQueueByLinkedList {
//用链表实现队列
private Node head = null;
private Node tail = head;
//1.入队列(尾插)
public boolean offer(int val){
Node newNode = new Node(val);
if(head == null){
head = newNode;
tail = newNode;
return true;
}
tail.next = newNode;
tail = tail.next;
return true;
}
//2.出队列(头删)
public Integer poll(){
if(head == null){
return null;
}
if(head.next == null){
Integer ret = head.val;
head = null;
return ret;
}
Integer ret = head.val;
head = head.next;
return ret;
}
//3.取队首元素
public Integer peek(){
if(head == null){
return null;
}
return head.val;
}
}