鱼C论坛

 找回密码
 立即注册
查看: 95|回复: 2

求助

[复制链接]
发表于 2025-10-23 18:47:01 | 显示全部楼层
  1. #include <stdio.h>
  2. #include <stdlib.h>

  3. /* 辅助函数:打印栈内容,形如 [1, 3, 4](自底向顶) */
  4. static void print_stack(const int *st, int top) {
  5.     putchar('[');
  6.     for (int i = 0; i <= top; ++i) {
  7.         if (i) printf(", ");
  8.         printf("%d", st[i]);
  9.     }
  10.     putchar(']');
  11. }

  12. /* 核心模拟:当 print_ops=1 时打印过程,=0 时仅判断合法性 */
  13. static int simulate_and_maybe_print(const int *b, int n, int print_ops) {
  14.     int *st = (int *)malloc(sizeof(int) * (n > 0 ? n : 1));
  15.     if (!st) {
  16.         fprintf(stderr, "内存分配失败\n");
  17.         exit(1);
  18.     }

  19.     int top = -1;       // 栈顶指针,-1 表示空
  20.     int nextPush = 1;   // 下一个要入栈的数(1..n)

  21.     for (int i = 0; i < n; ++i) {
  22.         int target = b[i];

  23.         // 不断入栈,直到栈顶等于 target 或者所有元素都已入栈
  24.         while (nextPush <= n && (top == -1 || st[top] != target)) {
  25.             st[++top] = nextPush;
  26.             if (print_ops) {
  27.                 printf("入栈 %d | 栈=", nextPush);
  28.                 print_stack(st, top);
  29.                 putchar('\n');
  30.             }
  31.             ++nextPush;
  32.         }

  33.         // 若此时栈顶是 target,则弹出;否则无法实现
  34.         if (top != -1 && st[top] == target) {
  35.             --top;
  36.             if (print_ops) {
  37.                 printf("出栈 -> %d | 栈=", target);
  38.                 print_stack(st, top);
  39.                 putchar('\n');
  40.             }
  41.         } else {
  42.             free(st);
  43.             return 0; // 非法
  44.         }
  45.     }

  46.     free(st);
  47.     return 1; // 合法
  48. }

  49. int main(void) {
  50.     int n;
  51.     if (scanf("%d", &n) != 1) return 0;
  52.     if (n < 0) return 0;

  53.     int *b = (int *)malloc(sizeof(int) * (n > 0 ? n : 1));
  54.     if (!b) {
  55.         fprintf(stderr, "内存分配失败\n");
  56.         return 1;
  57.     }

  58.     for (int i = 0; i < n; ++i) {
  59.         if (scanf("%d", &b[i]) != 1) {
  60.             free(b);
  61.             return 0;
  62.         }
  63.     }

  64.     // 先仅判定合法性
  65.     int ok = simulate_and_maybe_print(b, n, 0);

  66.     if (!ok) {
  67.         printf("否:该 b 序列不是以 1..n 为进栈序列的合法出栈序列。\n");
  68.     } else {
  69.         printf("是:该 b 序列可以由进栈序列 1..n 通过单栈操作得到。\n");
  70.         printf("操作过程:\n");
  71.         // 再次模拟,并打印全过程
  72.         simulate_and_maybe_print(b, n, 1);
  73.     }

  74.     free(b);
  75.     return 0;
  76. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-11-1 04:46

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表