栈,队列

#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
#define STACK_INIT_SIZE 2 //define后面不要加“;”
#define STACKINCREMENT 2
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);

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值