Choose a structure for a browser's Back button, then build it.
What to build
A history of pages, with the right structure behind it.
Requirements
visit NAMEopens a page.backreturns to the page that was open before the current one, and prints its name. If there is no earlier page, it printsnoneand the current page stays open.- After all the commands, print
now NAMEfor the page on show, ornow noneif no page was ever opened.
Input
The first line has q. Each of the next q lines has one command. A name has 1 to 15 lowercase letters.
Output
One line for each back, then the now line.
Constraints
1 ≤ q ≤ 100.
Example
Input:
5
visit home
visit news
visit sport
back
back
Output:
news
home
now home
Why it works
Going back always undoes the most recent visit, which is last in, first out. Naming the operations first, and only then picking the structure, is the habit this lesson teaches.
Examples
Example 1 · Input
5 visit home visit news visit sport back back
Expected output
news home now home
Example 2 · Input
2 back visit a
Expected output
none now a
Hints
Hint 1
The page you go back to is the one you visited most recently before this one, so use a stack.
Hint 2
visit pushes a page. back pops the current page, but only when there is another page under it.
Hint 3
The page on show is always the top of the stack.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
#include <string.h>
char pages[100][16];
int top = -1;
int main(void) {
int q;
scanf("%d", &q);
for (int i = 0; i < q; i++) {
char cmd[10];
scanf("%9s", cmd);
if (strcmp(cmd, "visit") == 0) {
top++;
scanf("%15s", pages[top]);
} else {
if (top < 1) {
printf("none\n");
} else {
top--;
printf("%s\n", pages[top]);
}
}
}
if (top == -1) printf("now none\n");
else printf("now %s\n", pages[top]);
return 0;
}