free的重要性 可以合并的堆栈!

在这里插入图片描述
在这里插入图片描述在这里插入图片描述
样例:

2
2 15
1 1 10
1 1 11
1 2 12
1 2 13
3 1 2
1 2 14
2 1
2 1
2 1
2 1
2 1
3 2 1
2 2
2 2
2 2
3 7
3 1 2
3 1 3
3 2 1
2 1
2 2
2 3
2 3

最开始没有free 所有点全部超 后来因为数组没有遍历free 最后一个点没过 下面放全对的

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

/**
 * 栈里放链表  不需要next
 */
struct node{
    struct node* pre;
    int number;
};
struct stack{
    struct node* head;
    struct node* last;
};

/**
 * @param x 堆栈数组指针
 * @param v 入栈索引
 * @param s 值
 */
void one(struct stack** x, int v,int s){
    struct node *insertNode=(struct node *)malloc(sizeof(struct node));
    insertNode->number=v;
    if(NULL==x[s]){
        x[s]=(struct stack *)malloc(sizeof(struct stack));
        x[s]->head=insertNode;
        x[s]->last=insertNode;
        insertNode->pre=NULL;
    } else{
        insertNode->pre=x[s]->last;
        x[s]->last=insertNode;
    }
}
/**
 * @param x 堆栈数组指针
 * @param s 出栈索引
 */
void two(struct stack** x,int s){
    printf("%d\n",x[s]->last->number);
    struct node *insertNode=x[s]->last;
    x[s]->last=x[s]->last->pre;
    if (!x[s]->last){
        x[s]=NULL;
        free(insertNode);
        return;
    }
    free(insertNode);
}
/**
 * @param x 堆栈数组指针
 * @param s 被加索引
 * @param v 叠加索引
 */
void three(struct stack** x,int s,int v){
    if (!x[s]){
        x[s]=(struct stack *)malloc(sizeof(struct stack));
        x[s]->head=x[v]->head;
        x[s]->last=x[v]->last;
    } else{
        x[v]->head->pre=x[s]->last;
        x[s]->last=x[v]->last;
    }
    free(x[v]);
    x[v]=NULL;
}
int main() {
    //n案例组数  s堆栈数,堆栈索引  v操作数,插入值,叠加索引  oc操作次数
    int n,s,v,oc;
    scanf("%d",&n);
    while(n--) {
        scanf("%d %d", &s, &oc);
        int f=s;
        struct stack **x=(struct stack **)malloc(sizeof(struct stack)*s);
        for (int i = 0; i <s ; ++i) {
            x[i]=NULL;
        }
        while(oc--){
            scanf("%d",&v);
            switch (v){
                case 1:{
                    scanf("%d %d", &s, &v);
                    one(x,v,s-1);
                    break;
                }
                case 2:{
                    scanf("%d",&s);
                    if (x[s-1]==NULL){
                        printf("EMPTY\n");
                    } else{
                        two(x,s-1);
                    }
                    break;
                }
                case 3:{
                    scanf("%d %d", &s, &v);
                    if (x[v-1]!=NULL){
                        three(x,s-1,v-1);
                    }
                    break;
                }
            }
        }
        for (int i = 0; i <f ; ++i) {
            free(x[i]);
        }
        free(x);
    }
    return 0;
}

malloc内存记得初始化

数组一定要遍历free

发布了22 篇原创文章 · 获赞 0 · 访问量 578

猜你喜欢

转载自blog.csdn.net/lixiang19971019/article/details/105361334