Is the actual stack itself "st"? How would I change what the node pointer (next?) is pointing to?Code:typedef struct node{ int data; struct node *next; }Node, *NodePtr; typedef struct{ NodePtr stack; }Stack, *StackPtr; Stack st;
Is the actual stack itself "st"? How would I change what the node pointer (next?) is pointing to?Code:typedef struct node{ int data; struct node *next; }Node, *NodePtr; typedef struct{ NodePtr stack; }Stack, *StackPtr; Stack st;
st is an instance of the Stack struct. However, all that struct contains is a pointer to struct node. There's no actual memory allocated for that one. To use that code you'd do something like this:
Code:{ Stack st; st.stack = malloc(sizeof(Node)); st.stack->data = 86; st.stack->next = NULL; }
If you understand what you're doing, you're not learning anything.
Here's a really simple implementation:
Code:#include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node *next; } Node, *NodePtr; typedef struct { NodePtr stack; } Stack, *StackPtr; void stack_init(StackPtr st) { st->stack = NULL; } void push(StackPtr st, int val) { NodePtr new; if(!(new = malloc(sizeof(Node)))) { puts("Memory allocation error!"); return; } new->data = val; new->next = st->stack; st->stack = new; } int pop(StackPtr st) { NodePtr node = st->stack; int val; if(!node) { puts("Stack underflow!"); return 0; } val = node->data; st->stack = node->next; free(node); return val; } int main(void) { Stack st; int vals[8] = { 86, 10, 37, 42, 7, 231, 53, 29 }; int i; stack_init(&st); for(i = 0;i < 8;++i) push(&st, vals[i]); for(i = 0;i < 8;++i) printf("%d\n", pop(&st)); return 0; }itsme@dreams:~/C$ ./stack
29
53
231
7
42
37
10
86
itsme@dreams:~/C$
If you understand what you're doing, you're not learning anything.