题目:
给定一串字符,不超过100个字符,可能包括括号、数字、字母、标点符号、空格,编程检查这- -串字符中的(),[],{}是否匹配。
思路
先将字符保存到链表中,然后再通过栈判断。
代码
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Node
{
char ls;
struct Node *next;
} Node;
int initLinkedList(Node * head)
{
if (head == NULL) { return 0; }
head -> next = NULL;
head -> ls = '\0';
return 1;
}
int ListInsert(Node *head, char ls) // 头插
{
Node *p = (Node *) malloc(sizeof(Node));
if (!p) { return 0; }
p -> next = head -> next;
p -> ls = ls;
head -> next = p;
return 1;
}
int initStack(Node *top) //名叫链栈,实为只能头插的单链表
{
if ( !top) { return 0;}
top -> next = NULL;
top -> ls = '\0';
return 1;
}
bool StackPush(Node *top, char ss)
{
Node *p = (Node *) malloc(sizeof (Node));
p -> ls = ss;
p -> next = top -> next;
top -> next = p;
return true;
}
bool StackPop(Node *top)
{
if (!top -> next) return false;
Node *p = top -> next;
if (!top -> next -> next) top -> next = NULL;
else top -> next = top -> next -> next;
free(p);
return true;
}
char StackGetTop(Node *top)
{
if ( !top -> next ) { return '\0'; }
return top -> next -> ls;
}
bool StackEmpty(Node *top, char ss)
{
if (top -> next == NULL) return true;
else return false;
}
int main()
{
int nums = 0, count;
char x, s, ls, ss, s_list, s_stack;
Node *stack = (Node *)malloc(sizeof(Node));
Node *head = (Node *) malloc(sizeof(Node));
initStack(stack);
initLinkedList(head);
printf("Please input ur calculation:\nPay attention, input when in Enlish mode.\nInput '#' when u finished please.\n");
while (true)
{
x= getchar();
if (x == '#') break;
if (x == '\r' or x == '\n') continue;
ListInsert(head, x);
nums ++;
}
Node * LinkedListPointer = head -> next;
for(int i = 0; i < nums; i ++)
{
if(!LinkedListPointer) {
printf("Oops…");
exit(0);
}
switch (LinkedListPointer->ls){
case ')':
StackPush(stack, LinkedListPointer->ls);
break;
case ']':
StackPush(stack, LinkedListPointer->ls);
break;
case '}':
StackPush(stack, LinkedListPointer->ls);
break;
case '>':
StackPush(stack, LinkedListPointer->ls);
break;
case '<':
s_stack = StackGetTop(stack);
StackPop(stack);
if (s_stack != '>') {
printf("Oops…");
exit(0);
}
break;
case '{':
s_stack = StackGetTop(stack);
StackPop(stack);
if (s_stack != '}'){
printf("Oops…");
exit(0);
}
break;
case '[':
s_stack = StackGetTop(stack);
StackPop(stack);
if (s_stack != ']') {
printf("Oops…");
exit(0);
}
break;
case '(':
s_stack = StackGetTop(stack);
StackPop(stack);
if (s_stack != ')') {
printf("Oops…");
exit(0);
}
break;
}
LinkedListPointer = LinkedListPointer->next;
}
printf("Match!");
return 1;
}
总结的很好,正好在学习数据结构