一 栈的实现
1使用顺序表去创建栈
public class MyStack009 {
//1使用顺序表去实现栈的基本操作,
int[] data=new int [100];
int size=0;
//1.0入栈
public void push(int val){
if(size>data.length){
return ;
}
data[size]=val;
size++;
}
//2.0出栈
public Integer pop(){
if(size==0){
return 0;
}
int result=data[size-1];
size--;
return result;
}
//3.0取栈顶元素
public Integer peek(){
if(size==0){
return 0;
}
return data[size-1];
}
}
2使用链表去创建栈
public class stack009 {
//使用链表来实现栈
class Node{
public int val;
public Node next;
public Node(int val) {
this.val = val;
}
}
public Node head=null;
//1.0入栈
public void push(int val){
Node newnode=new Node(val);
if(head==null){
head=newnode;
return;
}
newnode.next=head;
head=newnode;
}
//2.0出栈
public Integer poll(){
if(head==null){
return 0;
}
if(head.next==null){
int ret=head.val;
head=null;
return ret;
}
int ret=head.val;
head.next=head;
return ret;
}
//3.0取栈顶元素
public Integer peek(){
if(head==null){
return 0;
}
return head.val;
}
二 队列的实现
1使用链表实现
public class MyQueue0010 {
//1使用链表实现队列
class Node{
int val;
Node next;
public Node(int val) {
this.val = val;
}
}
//1入队
public Node head=null;
public Node tail=null;
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;
}
int ret=head.val;
if(head.next==null){
head=null;
return ret;
}
head=head.next;
return ret;
}
//3 取队收元素
public Integer peek(){
if(head==null){
return null;
}
return head.val;
}
}
2.使用顺序表去实现队列
public class MyQueue0011 {
//使用顺序表来实现队列
int[] data =new int[100];
int head=0;
int tail=0;
int size=0;
//1,入队列
public boolean offer(int val){
if(size==data.length){
return false;
}
data[tail]=val;
tail++;
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];
}
}