fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // スタックの要素ひとつを表す構造体
  5. typedef struct node {
  6. char data;
  7. struct node *next;
  8. } Node;
  9.  
  10. // intデータを保持するスタック
  11. typedef struct stack {
  12. Node *top;
  13. } Stack;
  14.  
  15. // スタックの初期化
  16. void initStack(Stack *s) { s->top = NULL; }
  17.  
  18. // プッシュ
  19. int push(Stack *s, char newdata) {
  20. Node *newNode = (Node *)malloc(sizeof(Node));
  21. if (newNode == NULL) { // メモリ領域の確保に失敗したとき
  22. return -1; // 異常値 -1 を呼び出し元に返す
  23. }
  24.  
  25. newNode->data = newdata;
  26. newNode->next = s->top;
  27. s->top = newNode;
  28. return 0;
  29. }
  30.  
  31. // スタックが空か?
  32. int isEmpty(Stack *s) { return s->top == NULL; }
  33.  
  34. // ポップ
  35. int pop(Stack *s, char *poppedData) {
  36. if (isEmpty(s)) {
  37. return -1;
  38. }
  39. Node *poppedNode = s->top;
  40. *poppedData = poppedNode->data;
  41. s->top = poppedNode->next;
  42. free(poppedNode);
  43. return 0;
  44. }
  45.  
  46. // ピーク
  47. int peek(Stack *s, char *topData) {
  48. if (isEmpty(s)) {
  49. return -1;
  50. }
  51. *topData = s->top->data;
  52. return 0;
  53. }
  54.  
  55. // スタックの内容を表示
  56. void printStack(Stack *s) {
  57. Node *current = s->top;
  58. while (current != NULL) {
  59. printf("%d ", current->data);
  60. current = current->next;
  61. }
  62. printf("\n");
  63. }
  64.  
  65. // メモリの解放
  66. void freeStack(Stack *s) {
  67. Node *current = s->top;
  68. while (current != NULL) {
  69. Node *tmp = current;
  70. current = current->next;
  71. free(tmp);
  72. }
  73. s->top = NULL;
  74. }
  75.  
  76. int checkParentheses(char str[]) {
  77. Stack s;
  78. initStack(&s);
  79. int result = 1;
  80.  
  81. for (int i = 0; str[i] != '\0'; i++) {
  82. char c = str[i];
  83. if (c == '(' || c == '[') {
  84. if (push(&s, c) != 0) {
  85. result = 0;
  86. break;
  87. }
  88. }else if (c == ')' || c == ']') {
  89. char popped;
  90. if (isEmpty(&s)) {
  91. result = 0;
  92. break;
  93. }
  94.  
  95. pop(&s, &popped);
  96. if (!((c == ')' && popped == '(') || (c == ']' && popped == '['))) {
  97. result = 0;
  98. break;
  99. }
  100. }
  101. }
  102.  
  103. if (result == 1 && !isEmpty(&s)) {
  104. result = 0;
  105. }
  106.  
  107. freeStack(&s); // スタックのメモリを解放
  108. return result;
  109. }
  110.  
  111. int main(void) {
  112. char str1[] = "(a[b(c)])";
  113. char str2[] = "([)]";
  114. char str3[] = "([()]";
  115.  
  116. printf("%s のチェック結果: %d\n", str1, checkParentheses(str1));
  117. printf("%s のチェック結果: %d\n", str2, checkParentheses(str2));
  118. printf("%s のチェック結果: %d\n", str3, checkParentheses(str3));
  119. return 0;
  120. }
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
(a[b(c)]) のチェック結果: 1
([)] のチェック結果: 0
([()] のチェック結果: 0