1. 顺序表
#include<stdio.h>
#include<stdlib.h>
typedef char ElementType;
#define MAXSIZE 10
typedef struct Stack {
ElementType data[MAXSIZE];
int top1;
int top2;
}*Stack;
Stack CreateStack();
void Push(Stack s, ElementType e, int tag);
void Pop(Stack s, ElementType *e, int tag);
Stack CreateStack() {
Stack s = (Stack)malloc(sizeof(struct Stack));
s->top1 = -1;
s->top2 = MAXSIZE;
return s;
}
void Push(Stack s, ElementType e, int tag) {
if ((s->top2 - s->top1) == 1) return;
if (tag == 0)
s->data[++s->top1] = e;
else
s->data[--s->top2] = e;
}
void Pop(Stack s, ElementType *e, int tag) {
if (tag == 1) {
if (s->top1 == -1) return;
*e = s->data[s->top1--];
}
else {
if (s->top2 == MAXSIZE) return;
*e = s->data[s->top2++];
}
}
typedef struct Stack {
ElementType data[MAXSIZE];
int top;
}*Stack;
Stack CreateStack();
void Push(Stack s, ElementType e);
void Pop(Stack s, ElementType *e);
Stack CreateStack() {
Stack s = (Stack)malloc(sizeof(struct Stack));
s->top = -1;
return s;
}
void Push(Stack s, ElementType e) {
if (s->top == MAXSIZE - 1) return;
s->data[++s->top] = e;
}
void Pop(Stack s, ElementType *e) {
if (s->top == -1) return;
*e = s->data[s->top--];
}
2. 链表
#include<stdio.h>
#include<stdlib.h>
typedef int ElementType;
typedef struct node *PtrToNode;
typedef struct node *Stack;
struct node {
ElementType data;
PtrToNode next;
};
Stack CreateStack();
void Push(Stack s, ElementType e);
void Pop(Stack s, ElementType *e);
Stack CreateStack() {
Stack s = (Stack)malloc(sizeof(struct node));
s->next = NULL;
return s;
}
void Push(Stack s, ElementType e) {
PtrToNode tmpCell = (PtrToNode)malloc(sizeof(struct node));
tmpCell->data = e;
tmpCell->next = s->next;
s->next = tmpCell;
}
void Pop(Stack s, ElementType *e) {
if (s->next == NULL) return;
PtrToNode firstCell = s->next;
*e = firstCell->data;
s->next = firstCell->next;
free(firstCell);
firstCell = NULL;
}