我最近发现了一个C拼图来编写一个程序来读取一组整数x 0,x 1,x 2,...... 直到a -1
输入为输入..
阅读后-1
,程序应打印每个相邻数字之间的差异.即,x 1 -x 0,x 2 -x 1,x 3 -x 2,......
例如:输入:
1 2 4 7 11 -1
产量
1 2 3 4
输出是(2-1),(4-2),(7-4),(11-7)的结果
问题是程序不应该使用数组.即使动态分配的数组也不行.
我尝试了很多,这是我带来的
#include<stdio.h>
int a, b;
int fn()
{
int r=b-a;
a=b;
scanf("%d", &b);
if(b!=-1)
{
printf("%d ", fn());
}
return r;
}
int main()
{
scanf("%d%d", &a, &b);
printf("%d ", fn() );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面的程序使用递归函数,但在这种方法中,因为它就像一个堆栈,所以最后打印的值是先打印的,而不是首先打印的值.
即,与上述相同输入的输出是:
4 3 2 1
而不是
1 2 3 4
有没有办法保存从这个调用堆栈中获取的值(如果我没有使用正确的术语,请纠正我)并再次将它们推入堆栈,以便在检索第一个计算值时,现在将是第一个被弹出的值?
例如:我得到了值4,3,2和1,fn()
因为它在4
弹出之前就像在堆栈上一样:
4 3 2 1
假设我弹出堆栈中的所有元素,并按照弹出的顺序将它们推送到另一个堆栈.然后新的堆栈将是
1 2 3 4
(即4
首先弹出并推动(因此最终在底部),然后3
弹出并推动等等.)
如果可以这样做,我们可以从新堆栈中弹出元素并按弹出顺序显示它们.
注意:我所指的堆栈是调用堆栈而不是显式创建的堆栈(可能需要数组).
或者也许有一种更简单的方法?
编辑:我需要输入和输出阶段是分开的而不是交错的.在输入结束之前,不应显示任何输出-1
.
编辑:程序无法使用文件存储输入以便稍后读回.
有没有办法保存从此调用堆栈中获取的值...并将它们再次推入堆栈,以便在检索第一个计算值时现在将第一个弹出?
每次读取数字(-1 除外)时递归。
创建一个由先前递归中的变量组成的链表。
除printf()
格式外未使用任何数组。
需要做更多的工作来避免最后打印后出现空格int
。
#include<stdio.h>
#include<stdlib.h>
typedef struct list {
const struct list *prev;
int i;
} list;
void print_list(const list *previous) {
if (previous && previous->prev) {
print_list(previous->prev);
printf("%d ", previous->i - previous->prev->i);
}
}
void JSfoo(const list *previous) {
list node = { previous, 0 };
int cnt = scanf("%d", &node.i);
if (cnt == 1 && node.i != -1) {
JSfoo(&node);
} else {
print_list(previous);
puts("");
}
}
int main(void) {
JSfoo(NULL);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出(非交错)
1 2 4 7 11 -1
1 2 3 4
Run Code Online (Sandbox Code Playgroud)
另一种方法是维护一个队列来消除递归打印的需要。相同的输出。
下面使用循环队列。注意只next
需要 1 个指针。队列句柄只需指向队列的末尾。不需要指向头部和尾部的指针。插入是O(1)
.
#include<stdio.h>
#include<stdlib.h>
typedef struct que {
struct que *next;
int i;
} que;
// Pass in the tail of the queue and return the updated tail
// `tail` points to the head. (Circular queue)
que *que_append(que *tail, que *node) {
if (tail) {
node->next = tail->next;
tail->next = node;
} else {
node->next = node;
}
return node;
}
void JSfoo(que *tail) {
que node;
int cnt = scanf("%d", &node.i);
if (cnt == 1 && node.i != -1) {
tail = que_append(tail, &node);
JSfoo(tail);
} else if (tail) {
que *head = tail->next;
while (head != tail) {
printf("%d ", head->next->i - head->i);
head = head->next;
}
puts("");
}
}
Run Code Online (Sandbox Code Playgroud)