繁体   English   中英

使用动态数组实现堆栈

[英]Implementing Stack using Dynamic Array

我已经使用动态数组(实现数组加倍)实现了一个Stack,但是当第二次发生加倍时,我遇到了运行时错误! 实施中出了什么问题? 请帮忙。

#include <stdio.h>
#include <stdlib.h>

struct Stack {
    int *arr;
    int top,size,capacity;
};

struct Stack *createStack(int capacity) {
    struct Stack *s = (struct Stack*)malloc(sizeof(struct Stack));
    s->arr = (int*)malloc(sizeof(int)*capacity);
    s->top = -1;
    s->capacity = capacity;
    s->size = 0;
    return s;
}

void doubleStack(struct Stack *s) {
    s->capacity = s->capacity*2;
    s->arr = realloc(s->arr,s->capacity);
    printf("Array doubling happened successfully!\n");
}

int isFull(struct Stack *s) {
    return s->size == s->capacity;
}

void push(struct Stack *s, int item) {
    if(isFull(s))
        doubleStack(s);

    printf("%d pushed!\n",item);
    s->arr[++(s->top)] = item;
    s->size++;
}

int isEmpty(struct Stack *s) {
    return s->size == 0;
}

void pop(struct Stack *s) {
    if(isEmpty(s)) {
        printf("Empty stack!\n");
        return;
    }

    int item = s->arr[(s->top)--];
    s->size--;
    printf("%d popped!\n",item);
}

int main(void) {
    struct Stack *s = createStack(2);
    push(s,1);
    push(s,2);
    push(s,3);
    push(s,4);
    push(s,5);
    pop(s);
    pop(s);
    return 0;
}

您无法将通过realloc()分配的realloc()sizeof(int)

尝试进行其他一些改进:

#include <stdio.h>
#include <stdlib.h>

struct Stack {
    int *arr;
    int top,size,capacity;
};

struct Stack *createStack(int capacity) {
    struct Stack *s = malloc(sizeof(struct Stack));
    s->arr = malloc(sizeof(int)*capacity);
    s->top = -1;
    s->capacity = capacity;
    s->size = 0;
    return s;
}

void destroyStack(struct Stack *s) {
    if(s != NULL) free(s->arr);
    free(s);
}

void doubleStack(struct Stack *s) {
    s->capacity = s->capacity*2;
    s->arr = realloc(s->arr,sizeof(int)*s->capacity);
    if(s->arr != NULL) {
        printf("Array doubling happened successfully!\n");
    } else {
        perror("realloc");
    }
}

int isFull(struct Stack *s) {
    return s->size == s->capacity;
}

void push(struct Stack *s, int item) {
    if(isFull(s))
        doubleStack(s);

    printf("%d pushed!\n",item);
    s->arr[++(s->top)] = item;
    s->size++;
}

int isEmpty(struct Stack *s) {
    return s->size == 0;
}

void pop(struct Stack *s) {
    if(isEmpty(s)) {
        printf("Empty stack!\n");
        return;
    }

    int item = s->arr[(s->top)--];
    s->size--;
    printf("%d popped!\n",item);
}

int main(void) {
    struct Stack *s = createStack(2);
    push(s,1);
    push(s,2);
    push(s,3);
    push(s,4);
    push(s,5);
    pop(s);
    pop(s);
    destroyStack(s);
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM