提示:以下是本篇文章正文内容,下面案例可供参考
一、堆栈结构和队列结构
1、什么是堆栈和队列?
堆栈和队列都是储存数据的结构,二者的不同在于储存方式不同,堆栈的储存是单开口,像是一个木桶,往里面放东西也只能从开口把东西拿出来,后进先出,队列是双开口,顺序储存数据,又顺序拿出数据,先进先出。 堆栈支持的操作:push pop 队列支持的操作:in out
2、堆栈和队列的结构
3、数组栈和链表栈的实现(java语言实现)
数组实现栈
public class stack
{
static final int CAPACITY=100;
int top;
int stack[];
public stack()
{
top = -1;
stack = new int[capacity];
}
}
public boolean push(int val)
{
if(top>=(capacity -1))
{
system.out.println("stack overdflow.");
return false;
}
stack[++top]=val;
return true;
}
public int pop()
{
if(top<0)
{
system.out.println("stack unflow");
return 0;
}
int element =tack[top--];
return element;
}
public int peek() { if(top<0) { system.out.println(“stack underflow”); return 0; } int element = stack[top]; return element; }
//empty判空 public boolean isempty() { return top<0; }
链表实现栈
public class ListStack { static class stackNode { int val; stackNode next;//节点 stackNode(int val)//节点的值 { this.val=val; }
} stackNode top;//因为栈的顺序是后进先出,因此链表栈只用记录头节点即可 public ListStack()//节点指针 { top =null; } }
//链表堆栈的push public void push(int val) { stackNode newNode =new stackNode(val); if(top ==null) { top = newNode; } else { stacNode temp = top; top = newNode; newNode.next= temp; } system.our.println(va+“is pushed to stack”); } //链表栈的pop public int pop() { if(top ==null) { system.our.println(“stack is empty”); return integer.min_value; } int poped = top.val; top = top.next; return poped; } //链式栈返回头节点 peek public int peek() { if(top ==null) { system.out.println(“stack is empty”); return integer.minvalue; } return top.val; } //判空方法 public boolean isEmpty() { return top ==null; }
4、数组队列和链表队列的实现(java语言实现)
数组实现队列
public class ArrayQueue
{
int front,rear,size;
int capacity;
int array[];
public ArrayQueue(int capacity)
{
this.capacity=capacity;
front=rear=size=0;
array=new int[capacity];
}
}
public void enqueue(int item)
{
if(isFull())return;
array[rear]=item;
rear=(rear+1)%capacity;
size++;
system.out.println(item+"is enqueue");
public int dequeue()
{
if(isEmpty())
return Integer.min_value;
int item=array[front];
front =(front +1)%capacity;
size--;
return item;
}
}
public int peek()
{
if(isempty())
return integer.min_value;
return array[front];
public boolean isFull()
{
return size == capacity;
}
public boolean isEmpty()
{
return size ==0;
}
}
链式实现队列
public class ListQueue
{
QueueNode front;
QueueNode rear;
static class QueueNode
{
int value;
QueueNode next;
public QueueNode(int value)
{
this.value=value;
}
}
}
public void enqueue(int value)
{
QueueNode newNode = new QueueNode(value);
if(this.rear==null)
{
this.front=this.rear=newNode;
return;
}
this.rear.next=newNode;
this.rear=newNode;
}
public int dequeue()
{
if(this.front==null)
{
system.out.println("the queue is empty");
return integer.min_value;
}
QueueNode frontNode =this.front;
this.front =this.front.next;
if(this.front==null)
{
this.rear=null;
}
return frontNode.value;
}
|