Stack.c - OpenLearning
// Stack.c
// Mohammad Ghasembeigi
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <malloc.h>

#include "Stack.h"

#define TRUE 1
#define FALSE 0

typedef struct _node *Node;

struct _stack {
    int elements;
    Node pNext;
};

struct _node {
    char c;
    Node pNext;
};

//Func Declarations
Node lastNode(Stack s);
Node createNode (int c);

//create a new stack with nothing in it
Stack createStack(void) {
    Stack newStack = malloc( sizeof( struct _stack));
    assert(newStack != NULL); //Check if memory was given

    //intitilise
	newStack->elements = 0;
	newStack->pNext = NULL;

    return newStack;
}

//create node
Node createNode (int c) {
	Node newNode = malloc(sizeof (struct _node));
	assert(newNode != NULL);

	//initilise
	newNode->c = c;
	newNode->pNext = NULL;

	return newNode;
}

//is the Stack empty?
int isEmpty(Stack s) {
    int isEmpty = FALSE;
    if (s->elements == 0) { //if elements is zero, stack is empty
        isEmpty = TRUE;
    }
    return isEmpty;
}

//dispose of a Stack we no longer need
void disposeStack(Stack s) {
    free(s);
}

//return the value at the top of the Stack
int top(Stack s) {
    //find current last node
	Node last = lastNode(s);

	return last->c;
}

//remove the top of the Stack
void pop(Stack s) {

    Node last = lastNode(s);

    //dispose of last node
    free(last);

    //decreate elements number
	s->elements--;

    //Find new last element
    last = lastNode(s);
    last->pNext = NULL; //make it point to a NULL
}

//push a value onto the top of the Stack
void push(Stack s, int value) {
    //make new node, add to top
	Node newNode = createNode (value);

	//find current last node
	Node last = lastNode(s);

    last->pNext = newNode;

    //increment elements number
	s->elements++;
}

//return pointer to last node or the pointer in the last node which points to NULL
//if stack is empty (has no nodes) a pointer to the stack is returned instead
Node lastNode(Stack s) {

    //Set up blank new node
    Node node = NULL;

    //Set up other nodes
    Node cur;
    Node prev;
	
	//Store elemnent number and if stack is empty
    int elements = s->elements;
    int emptyStack = isEmpty(s);
      
	prev = s; //make prev point to stack just incase stack is empty
	cur = s->pNext; //make cur pointer point to next node and make previous equal cur for now
	

	int counter = 0;

	while (cur != NULL && counter < elements) {       //while the cur node doesn't point to a NULL
		prev = cur;            //reserve the current node by assigning its value to prev
		cur = cur->pNext;      //make cur the next pointer in linked list
		counter++;
	}

    //Return prev which contains pointer to the last node
	return prev;
}

Download file: Stack.c (2.8 KB)

Comments

Chat