栈:先进后出;可用数组或链表实现

cs
#include<stdlib.h>
#define MaxSize 5
typedef struct{
int data[MaxSize];
int top;
}Stack;
//初始化栈
void init(Stack *stack){
stack->top=-1;
}
//入栈操作
void push(Stack *stack,int value){
if(stack->top==MaxSize-1){
printf("栈已满,无法插入数据");
return;
}
stack->top=stack->top+1;
stack->data[stack->top]=value;
}
//出栈操作
void pop(Stack *stack){
if(stack->top==-1){
printf("栈已空");
return;
}
printf("%d",stack->data[stack->top]);
stack->top--;
}
链表实现栈
cs
typedef struct node{
int data;
struct node *next;
}Node;
void init(Node *head){
head->next=NULL;
}
//入栈
void pushNode(Node *head,int value){
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data=value;
newNode->next=NULL;
newNode->next=head->next;
head->next=newNode;
}
//出栈
void popNode(Node *head){
if(head->next==NULL){
return;
}
Node *temp=head->next;
printf("%d\n",temp->data);
head->next=temp->next;
}
int main(){
Node *head=(Node *)malloc(sizeof(Node));
init(head);
pushNode(head,2);
pushNode(head,4);
pushNode(head,8);
pushNode(head,11);
popNode(head);
popNode(head);
}
数组实现队列


判断入栈出栈的合法性

cs
bool validateStackSequences(int* pushed, int pushedSize, int* popped, int poppedSize) {
int *s=(int *)malloc(pushedSize*sizeof(int));
int j=0;
int top=-1;
for(int i=0;i<poppedSize;i++){
top++;
s[top]=pushed[i];
while(top!=-1 && s[top]==popped[j]){
j++;
top--;
}
}
if(top!=-1){
return false;
}else{
return true;
}
}