栈
1.创建并初始化
typedef struct Stack{
char data[MAXSIZE];
int top;
}Stack;
void InitStack(Stack *s){
s->top=-1;
}
2.入栈
void InitStack(Stack *s){
s->top=-1;
}
//Function to push an element into the stack
void Push(Stack *s,char x){
if(s->top==MAXSIZE-1){
printf("Stack is full\n");
exit(1);
}
//入栈操作
s->data[++s->top]=x; //将元素x存储在栈顶指针递增后的位置
}
3.出栈
char Pop(Stack *s){
if(s->top==-1){
//printf("Stack is empty\n");
exit(1);
}
//出栈操作
return s->data[s->top--]; //返回栈顶元素并将栈顶指针递减
}
队列
1.创建新队列(结点;首尾指针)
typedef struct node{
int data;
struct node *next;
}Node;
typedef struct queue{
Node *front;
Node *rear;
}Queue;
2.初始化队列
void InitQueue(Queue *q){
q->front = q->rear = (Node *)malloc(sizeof(Node));
q->front->next = NULL;
}
3.入队
void push(Queue *q, int x){
Node *p = (Node *)malloc(sizeof(Node));
p->data = x;
p->next = NULL; //新结点指针域为空
q->rear->next = p; //尾插法
q->rear = p; //更新尾指针
}
4.出队
int pop(Queue *q){
if(q->front == q->rear) {
printf("Invalid\n");
return -1; //队列为空
}
Node *p = q->front->next;
int x = p->data;
q->front->next = p->next;
if(q->rear == p) q->rear = q->front; //若队列中只有一个元素,删除后更新尾指针
free(p);
return x;
}
5.求队列长度
int size(Queue *q){
int Size = 0;
Node *p = q->front->next;
while(p){
Size++;
p = p->next;
}
return Size;
}