棧
棧
:只允許在一端進行插入或刪除操作的線性表。通過只操作top
從而實現先進後出
的特點。
結構體
#define MaxSize 50 //定義棧中元素的最大個數
typedef struct{
Elemtype data[MaxSize]; //存放棧中元素
int top; //棧頂指針
}SqStack;
源碼實現
#include <iostream>
#define MaxSize 50 //定義棧中元素的最大個數
using namespace std;
class MyStack
{
private:
int data[MaxSize];
public:
int top;
MyStack(){
top = -1;
};
~MyStack(){};
bool IsEmpty(){
if(top == -1)
return true;
else
return false;
}
bool Mpush (int x){
if(top == MaxSize-1)
return false;
data[++top] = x;
return true;
}
bool Mpop(){
if(top == -1)
return false;
top--; //靠覆蓋實現數據的刪除
return true;
}
bool GetTop(int &x){
if(top == -1)
return false;
x = data[top];
return true;
}
};
int main()
{
MyStack mStack; //構造函數會在實例化的時候自動調用
for(int i=1; i<6; i++)
mStack.Mpush(i);
mStack.Mpop();
int mtop;
mStack.GetTop(mtop);
cout<<mtop<<endl;
cout<<mStack.top<<endl;
}
隊列
隊列
:只允許在表的一端進行插入,而在表的另一端進行刪除操作的線性表。通過操作front
與rear
兩個元素,從而實現先進先出
的特點。
結構體
#define MaxSize 50 //定義隊列中元素的最大個數
typedef struct{
Elemtype data[MaxSize]; //存放隊列元素
int front,rear; //隊頭指針和隊尾指針
}SqQueue;
源碼實現
#include <iostream>
using namespace std;
#define MaxSize 50 //定義棧中元素的最大個數
class MyQueue
{
private:
int data[MaxSize];
public:
int front;
int rear;
MyQueue(){
front=rear=0;
};
~MyQueue(){};
bool IsEmpty(){
if(front == rear)
return true;
else
return false;
}
bool IsFull(){
//防止隊空與隊滿均出現rear == front所以rear指向下一個位置
if((rear+1)%MaxSize == front)
return true;
else
return false;
}
bool EnQueue (int x){
if(!IsFull())
{
data[rear] = x;
rear = (rear+1)%MaxSize; //操作隊尾
return true;
}else
return false;
}
bool Dequeue(int &x){
if(IsEmpty())
return false;
else{
x = data[front];
front = (front+1)%MaxSize; //操作隊頭
return true;
}
}
};
int main()
{
MyQueue myQueue;
for(int i=0;i<5;i++)
myQueue.EnQueue(i);
int x,i=0;
while(i++<3)
myQueue.Dequeue(x);
cout<<x<<endl;
}