第一个测试点“()”我的力扣老是不对,我在codeblocks上测试了下,觉得没问题呀,不过因为是在codeblocks上和力扣不一样,所以我增加了main函数
力扣上:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define true 1
#define false 0
typedef int E;
struct Stack{
char val;
struct Stack* next;
char top;
};
typedef struct Stack* ListStack;
_Bool initStack(ListStack stack){
stack = (struct Stack*)malloc(sizeof(struct Stack));
if(stack==NULL) return false;
stack->next = NULL;
return true;
}
_Bool push(ListStack stack, char element){
ListStack tmp = stack->next,new;
new = (struct Stack*)malloc(sizeof(struct Stack));
if(new == NULL) return false;
new->val = element;
new->next = tmp;
stack->next = new;
stack->top = element;
return true;
}
char pop(ListStack stack){
ListStack tmp = stack->next;
stack->next = stack->next->next;
char result = tmp->val;
free(tmp);
return result;
}
int isEmpty(ListStack stack){
if(stack->next==NULL) return 1;
else return 0;
}
_Bool isValid(char * s){
unsigned long len = strlen(s);
struct Stack stack;
initStack(&stack);
int i;
if(len%2==1) return false;
for(i=0;i<len;i++){
if(s[i]=='{' || s[i]=='[' || s[i]=='('){
push(&stack,s[i]);
}else{
if(isEmpty(&stack)) return false;
if(s[i]=='}'){
if(pop(&stack)!='{') return false;
}else if(s[i]==']'){
if(pop(&stack)!='[') return false;
}else{
if(pop(&stack)!='(') return false;
}
}
}
if(isEmpty(&stack)) return true;
else return false;
}
codeblocks上:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define true 1
#define false 0
typedef int E;
struct Stack{
char val;
struct Stack* next;
char top;
};
typedef struct Stack* ListStack;
_Bool initStack(ListStack stack){
stack = (struct Stack*)malloc(sizeof(struct Stack));
if(stack==NULL) return false;
stack->next = NULL;
return true;
}
_Bool push(ListStack stack, char element){
ListStack tmp = stack->next,new;
new = (struct Stack*)malloc(sizeof(struct Stack));
if(new == NULL) return false;
new->val = element;
new->next = tmp;
stack->next = new;
stack->top = element;
return true;
}
char pop(ListStack stack){
ListStack tmp = stack->next;
stack->next = stack->next->next;
char result = tmp->val;
free(tmp);
return result;
}
int isEmpty(ListStack stack){
if(stack->next==NULL) return 1;
else return 0;
}
_Bool isValid(char * s){
unsigned long len = strlen(s);
struct Stack stack;
initStack(&stack);
int i;
if(len%2==1) return false;
for(i=0;i<len;i++){
if(s[i]=='{' || s[i]=='[' || s[i]=='('){
push(&stack,s[i]);
}else{
if(isEmpty(&stack)) return false;
if(s[i]=='}'){
if(pop(&stack)!='{') return false;
}else if(s[i]==']'){
if(pop(&stack)!='[') return false;
}else{
if(pop(&stack)!='(') return false;
}
}
}
if(isEmpty(&stack)) return true;
else return false;
}
int main(){
char s[10] = "()";
if(isValid(s)) printf("true");
else printf("false");
}
显示为"true"