栈
typedef int ElemType;
typedef struct {
ElemType *base;
ElemType *top;
int stacksize;
}SqStack;
SqStack InitStack(void) {
SqStack s;
s.base = (ElemType*)malloc((STACK_INIT_SIZE)*sizeof(ElemType));
if (!s.base) { printf("内存分配失败\n"); exit(-1); }
s.top = s.base;
s.stacksize = STACK_INIT_SIZE;
return s;
}
void push(SqStack &s, ElemType e) {//注意这里是引用传递,不加&便成了值传递
if (s.top - s.base >= s.stacksize) {
s.base = (ElemType*)realloc(s.base, (s.stacksize + STACKINCREMENT) * sizeof(ElemType));
if (!s.base) { printf("内存分配失败\n"); exit(-1); }
s.top = s.base + s.stacksize;//这一句很难懂,因为realloc后,
s.stacksize += STACKINCREMENT;//s.base很有可能整体挪窝,而挪窝后
} //s.top还指向原来的区域
*s.top = e; s.top++;
}
void main() {
SqStack s = InitStack();
push(s, 1);
printf("此时top-base=%d\n", s.top - s.base);
printf("此时 s.stacksize:%d\n", s.stacksize);
push(s, 2);
printf("此时top-base=%d\n", s.top - s.base);
printf("此时 s.stacksize:%d\n", s.stacksize);
push(s, 3);
printf("此时top-base=%d\n", s.top - s.base);
printf("此时 s.stacksize:%d\n", s.stacksize);
ElemType* p = s.base;
while (p != s.top) {
printf("值为%d\n",*p);
p++;
}
}
队列
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef int ElemType;
typedef struct QNode{
ElemType data;
struct QNode * next;
}QNode,*QueuePtr;
typedef struct {
QueuePtr front;
QueuePtr rear;
}LinkQueue;
LinkQueue InitQueue(void) {
LinkQueue q;
q.front = q.rear=(QueuePtr)malloc(sizeof(QNode));
if (!q.front) { printf("分配内存失败\n"); exit(-1); }
q.front->next =NULL;
return q;
}
void EnQueue(LinkQueue& q, ElemType e) {
QueuePtr p = (QueuePtr)malloc(sizeof(QNode));
p->data = e;
p->next = NULL;
q.rear->next = p;
q.rear = p;
}
void main() {
LinkQueue q = InitQueue();
EnQueue(q, 1);
EnQueue(q, 2);
QueuePtr p = q.front->next;
while (p!=NULL) {
printf("值为:%d\n", p->data);
p = p->next;
}
free(p);
}