Skip to content

Instantly share code, notes, and snippets.

@flavius
Forked from paulbarbu/functions.c
Created July 24, 2011 17:01
Show Gist options
  • Save flavius/1102822 to your computer and use it in GitHub Desktop.
Save flavius/1102822 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
#include "stack.h"
void push(struct node** first, struct node** addAfter, const char val){
struct node* top;
top = malloc(sizeof(struct node*));
top->val = val;
if(*first == NULL){
*first = top;
*addAfter = *first;
}
else{
(*addAfter)->next = top;
*addAfter = top;
}
}
char pop(struct node** first, struct node** last){
struct node* t;
if(*first == *last){
*first = *last = NULL;
return '\0';
}
for(t = *first; t != *last; t = t->next){
if(t->next == *last){
t->next = NULL;
*last = t;
break;
}
}
return t->val;
}
int isEmpty(struct node** first){
return *first == NULL;
}
void showStack(struct node* first){
struct node* t = NULL;
for(t = first; t != NULL; t = t->next){
printf("%c", t->val);
}
printf("\n");
}
int match(const char current, const char last){
int current_ascii, last_ascii;
current_ascii = current;
last_ascii = last;
if(current_ascii == (last_ascii + 1)){
return 1;
}
return 0;
}
#ifndef HGUARD_FUNC
#define HGUARD_FUNC
int isEmpty(struct node** first);
void push(struct node** first, struct node** last, const char val);
char pop(struct node** first, struct node** last);
void showStack(struct node* first);
int match(char current, char last);
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "stack.h"
#include "functions.h"
struct node *first = NULL, *last = NULL;
int main(void){
char* stringTest = " ((( ()) ))";
int i;
for(i = 0; i < strlen(stringTest); i++){
if(last == NULL){
push(&first, &last, stringTest[i]);
}
else if(match(stringTest[i], last->val)){
pop(&first, &last);
}
else{
push(&first, &last, stringTest[i]);
}
}
if(isEmpty(&first)){
printf("Matched!\n");
}
else{
showStack(first);
}
return EXIT_SUCCESS;
}
#ifndef H_GUARD_STACK
#define H_GUARD_STACK
struct node{
char val;
struct node* next;
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment