Created
August 13, 2013 08:34
-
-
Save sjoness/6219073 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Author: Sam Jones | |
* Description: Stack revision | |
* Created: 18/04/2013 | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
typedef struct node { | |
int item; | |
struct node *next; | |
} Node; | |
typedef struct { | |
Node *top; | |
int size; | |
} Stack; | |
void initialise(Stack *s) { | |
// this function is to initialise the stack | |
s->size = 0; // set the size of the stack to 0 | |
s->top = NULL; // top of the stack now points to NULL | |
} | |
void push(Stack *s, int value) { | |
// Push function to add data to the top of the stack | |
Node *np; // make a node pointer | |
np = (Node *)malloc(sizeof(Node)); // we now have some space for a node | |
if (np == NULL) { | |
// The program will crash if the memory was not allocated | |
exit(1); | |
} | |
np->item = value; // put the value we want to allocate in the node | |
np->next = s->top; // copy the last address that was at the top of the stack | |
s->top = np; // now the top is pointing to the new top of the stack | |
// increment the size of the stack count | |
s->size++; | |
} | |
int pop(Stack *s) { | |
// Pop function to remove data to the top of the stack | |
int temp; | |
Node *np; | |
if (s->top == NULL) { | |
// The program will crash if the stack is empty | |
exit(1); | |
} | |
np = s->top; // node pointer is now pointing to the top of the stack | |
temp = s->top->item; // store the valuse currently at the top of the stack | |
s->top = np->next; // make the top of the stack point to the node below | |
s->size--; // decrement the size of the stack count | |
free(np); // free the memory at the address the np is pointing to | |
return temp; // return the value that was popped off the stack | |
} | |
int main() { | |
int pv; // make a pop value variable | |
Stack stk; // this is a stack object | |
initialise(&stk); // initialise the data structure to 0 | |
push(&stk, 7); // push the value 7 on to the stack | |
push(&stk, 9); // push the value 9 on to the stack | |
// The stack now contains 9, 7 and NULL | |
pv = pop(&stk); | |
// the value 9 has been popped off the stack so now only 7 and NULL remains | |
pv = pop(&stk); | |
// the value 7 has been popped off the stack so now only NULL remains | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment