题目描述
众所周知,计算机程序中通常含有许多的函数调用,而调用关系往往是嵌套的,也就是说被调用的函数可能会调用另一个函数,这导致我们常常在debug的时候遇到困难,并希望能弄清楚其上层的一系列调用关系。
在这道题目中,我们会给定一篇代码,并希望你能找到指定函数第一次被调用时的调用链,将其打印出来;当然,你有可能会发现给定的函数没有在代码中出现,那么你应该打印一行“NOT REFERENCED”并结束你的程序。
为了降低难度,给定的代码是经过极度简化的,它只包括函数调用和返回语句(表示退出这层调用),并且没有任何额外的语法格式。
输入
第一行是一个数字 N,代表代码共有 N 行;
接下来的 N 行,第 i+1 行是一个字符串 S[i],代表第 i 行代码:
1. 这行代码是一个函数调用,那么它的形式类似“fun()”;
2. 这行代码是返回语句,它的内容固定为“return”;
第 N+2 行是一个字符串,代表欲寻找到的函数。
(0<N≤100000,0<|S[i]|≤110;给定的被调用函数名保证合法,其一定以“()”结尾并只由大小写字母和下划线组成)
输出
输出一行:
1. 如果指定的函数在代码中出现了,那么打印出其调用关系链,用“->”连接;
2. 否则,打印一行“NOT REFERENCED”。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 300
typedef struct Stack {
char **data;
int top, size;
} Stack;
Stack* initStack(int n) {
Stack *s = (Stack *)malloc(sizeof(Stack));
s->data = (char **)malloc(sizeof(char*)*n);
s->top = -1;
s->size = n;
return s;
}
int push(Stack *s, char *str) {
if (s->top == (s->size - 1)) return 0;
s->data[s->top + 1] = (char *)malloc(sizeof(char) * MAX);
if (strcpy(s->data[s->top + 1], str)) s->top += 1;
else return 0;
return 1;
}
int empty(Stack *s) {
return s->top == -1;
}
int pop(Stack *s) {
if (empty(s)) return 0;
free(s->data[s->top]);
s->top -= 1;
return 1;
}
int find(Stack *s, char *str) {
if (empty(s)) return -1;
int pos = s->top;
while (pos != -1) {
if (!strcmp(s->data[s->top], str)) break;
pos -= 1;
}
if (pos == -1) return -1;
return pos;
}
void printStack(Stack *s, int pos) {
for (int i = 0; i < pos; i++) {
printf("%s -> ", s->data[i]);
}
printf("%s\n", s->data[pos]);
return ;
}
void freeStack(Stack *s) {
if (s->top == -1) return ;
for (int i = 0; i < s->top; i++) {
free(s->data[i]);
}
return ;
}
void clear(Stack *s) {
if (!empty(s)) freeStack(s);
free(s);
return ;
}
int main(void) {
int n = 0;
scanf("%d", &n);
Stack *s = initStack(n);
for (int i = 0; i < n; i++) {
char str[MAX];
scanf("%s", str);
if (strcmp(str, "return")) push(s, str);
else pop(s);
}
char str[MAX];
scanf("%s", str);
int pos = find(s, str);
if (pos == -1) printf("NOT REFERENCED");
else printStack(s, pos);
clear(s);
return 0;
}
测试样例可以通过,但是提交后显示异常,期待大神能帮忙找出问题