Stack with linked list, working, but I know I'm doing something dirty!
I finally got it working, but I'm not satisfied because I'm not freeing the memory myself. I'm not really sure what to do and was hoping to get a little advice.
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct list{
char element;
struct list * node;
} list;
int push(int data, list **ptr){
list * tmp;
tmp = malloc(sizeof(list));
tmp->node = (*ptr)->node;
tmp->element = data;
(*ptr)->node = tmp;
return 0;
}
int pop(list **ptr){
if( (*ptr)->node != NULL ){
int tmp;
tmp = (*ptr)->node->element;
free((*ptr)->node); //should be here I found out
(*ptr)->node = (*ptr)->node->node;
//free((*ptr)->node); causes junk data?
return tmp;
} else {
fputs("Mismatched pop!\n",stderr);
exit(1);
}
}
int main(){
list * head;
head = malloc(sizeof(list));
int i;
for(i = 0;i<=10;i++)
push(i,&head);
for(i = 0;i<=10;i++)
printf("%d\n",pop(&head));
return 0;
}
Wow, I just figured it out, stupid mistake. Anyways, if anyone could at least check it to see if there are any other dirty tricks I pulled I'd be grateful.