Using custom stack implemented by C


  • 0
    Y
    typedef char StackElementT;
    /*Data structure based on array*/
    typedef struct Stack {
    	StackElementT* data;
    	int top;
    	int maxSize;
    }Stack;
    
    Stack* initStack(size_t size) {
    	Stack* stack = (Stack*)malloc(sizeof(Stack));
    	stack->data = (StackElementT*)malloc(size*sizeof(StackElementT));
    	if (stack->data == NULL) {
    		fprintf(stderr, "Insufficient memory to initialize stack.\n");
    		exit(1);  /* Exit, returning error code. */
    	}
    	stack->maxSize = size;
    	stack->top = -1;
    
    	return stack;
    }
    void destoryStack(Stack* stack){
    	free(stack->data);
    	stack->data = NULL;
    	stack->maxSize = 0;
    	stack->top = -1;
    	free(stack); stack = NULL;
    }
    bool stackFull(Stack* stack) {
    	return stack->top == (stack->maxSize - 1);
    }
    bool stackEmpty(Stack* stack) {
    	return stack->top == -1;
    }
    void push(Stack* stack, StackElementT data) {
    	if(!stackFull(stack)){
    		stack->top++;
    		stack->data[stack->top] = data;
    	}
    	else {
    		fprintf(stderr, "Cannot push data into full stack.\n");
    	}
    }
    char pop(Stack* stack) {
    	if (stackEmpty(stack)) {
    		fprintf(stderr, "Can't pop element from stack: stack is empty.\n");
    		return 0;
    	}
    	return stack->data[stack->top--];
    }
    
    bool isValid(char* s) {
    	bool valid = false;
    	int len = strlen(s);
    	if (len % 2 != 0) return valid;
    	//char sb[] = {};
    	Stack* q = initStack(len);
    	for (int i = 0; i < len;i++){
    		if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
    			push(q, s[i]);
    		}
    		else{
    			char data = pop(q);
    			switch (data){
    			case '(':
    				if (s[i] != ')') {
    					destoryStack(q);
    					return false;
    				}
    				break;
    			case '[':
    				if (s[i] != ']') {
    					destoryStack(q);
    					return false;
    				}
    				break;
    			case '{':
    				if (s[i] != '}') {
    					destoryStack(q);
    					return false;
    				}
    				break;
    			default:
    				destoryStack(q);
    				return false;
    			}
    		}
    
    	}
    	if (stackEmpty(q))
    		valid = true;
    
    	destoryStack(q);
    	return valid;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.