1,链栈(用链表实现栈)
>1,初始化栈
class Entry{
int data;
Entry next;
public Entry(){
this.data = -1;
this.next = null;
}
public Entry(int val){
this.data = val;
this.next = null;
}
}
public Entry head = null;
public LinkStack(){
this.head = new Entry();
}
>2,入栈
public void push(int val){
Entry entry = new Entry(val);
entry.next = head.next;
head.next = entry;
}
>3,判断栈空
public boolean isEmpty(){
if(head.next == null)
return true;
return false;
}
>4,出栈
public boolean pop(){
if(isEmpty()){
return false;
}
head.next = head.next.next;
return true;
}
>5,得到栈顶元素
public int gettop(){
if(isEmpty()){
return -1;
}
return head.next.data;
}
2,队列
队列:只能在表的一端进行插入运算,在表的另一端进行删除运算的线性表 (头删尾插)
(两个栈实现队列)
1,初始化两个栈
Stack s1 = new Stack();
Stack s2 = new Stack();
2,入队
将数据入到s1这个栈里
//入队
public void pushQ(int val){
if(s1.isFull()){
return;
}
s1.push(val);
}
3,出队
将S1栈里的数据出栈到S2中,(注意要保留s1栈低的数)再将s2倒入s1 ,覆盖s1 栈低的那个元素。就实现了出队
------》
//出队
public void popQ(){
if(s1.isEmpty()){
return;
}
while(s1.top > 1){
s2.push(s1.gettop());
s1.top--;
}
s1.top = 0;
while(!s2.isEmpty()){
s1.push(s2.gettop());
s2.top--;
}
}
3,得到队顶元素//得到队顶元素
public int gettop(){
return s1.elem[0];
}
3,循环队列
顺序队“头删尾插”容易产生“假溢出”
当尾指针已经到了数组的上界,不能再有入队操作,但其实数组中还有空位置,这就叫“假溢出”。
所以我们将采用---循环队列---来解决假溢出
在循环队列中,空队特征是front=rear;队满时也会有front=rear;
解决方案:
人为浪费一个单元,令队满特征为front=(rear+1)%N;
空条件 : front = rear
队满条件: front = (rear+1) % N (N=allsize)
队列长度:L=(N+rear-front)% N
循环队列的操作-------
1,初始化
int[] elem;
int front;//队首
int rear;//队尾
int usedSize = 0;//当前循环队列内部有效数据个数
int allSize = 10;
public QueueLink(){
this(10);
}
public QueueLink(int size){
this.elem = new int[size];
this.front = 0;
this.rear = 0;
}
2,队满//判断是否为满的方法
public boolean isFull(){
if((this.rear+1) % this.allSize == this.front)
return true;
return false;
}
3,入队
public void push(int val){
if(isFull()){
return;
}
this.elem[this.rear] = val;
this.rear = (this.rear+1) % this.allSize;
this.usedSize++;
}
4,队空
public boolean isEmpty(){
return this.front == this.rear;
}
5,出队
//出队
public void pop(){
if(isEmpty()){
return;
}
this.elem[this.front] = -1;
this.front = (this.front+1) % this.allSize;
this.usedSize--;
}
6,得到队头元素
//得到队头元素
public int gettop(){
if(isEmpty()){
return -1;
}
return this.elem[this.front];
}
7,打印队列元素
public void show(){
for(int i = this.front;i != this.rear;i = (i+1) % this.allSize){
System.out.print(this.elem[i]+" ");
}
System.err.println();
}