A Stack Implemented as a linked structure in C


Header file for a list
//---------------------------------------------------------------
// File: Code126_Stack.h
// Purpose: Header file for a demonstration of a stack implemented 
//		as a linked structure.  Data type: Character
// Programming Language: C
// Author: Dr. Rick Coleman
//---------------------------------------------------------------
#ifndef CODE126_STACK_H
#define CODE126_STACK_H

#include <stdio.h>

// Define a structure to be used as the stack item
struct StackItem
{
	char             ch;
	struct StackItem *next;
};

// List Function Prototypes
void InitStack();         // Initialize the stack
void ClearStack();        // Remove all items from the stack
int Push(char ch);        // Push an item onto the stack
char Pop();               // Pop an item from the stack
int isEmpty();            // Return true if stack is empty
int isFull();             // Return true if stack is full

// Define TRUE and FALSE if they have not already been defined
#ifndef FALSE
#define FALSE (0)
#endif
#ifndef TRUE
#define TRUE (!FALSE)
#endif

#endif // End of stack header

Implementation (.c) file for a stack
//---------------------------------------------------------------
// File: Code126_Stack.c
// Purpose: Implementation file for a demonstration of a stack  
//		implemented as a linked structure.  Data type: Character
// Programming Language: C
// Author: Dr. Rick Coleman
// Date: January 21, 2002
//---------------------------------------------------------------
#include <stdlib.h>	// To get access to malloc()
#include "Code126_Stack.h"

// Declare this as static so no code outside of this source
// can access it.
static struct StackItem *top;	// Declare global pointer to top of the stack

//--------------------------------------------
// Function: InitStack()
// Purpose: Initialize stack to empty. Use only
//		with a new stack.
// Precondition: Stack must not contain any
//		nodes. 
// Returns: void
//--------------------------------------------
void InitStack()
{
	top = NULL;
}

//--------------------------------------------
// Function: ClearStack()
// Purpose: Remove all items from the stack
// Returns: void
//--------------------------------------------
void ClearStack()
{
	struct StackItem *temp;

	if(!isEmpty())
	{
		temp = top;

		// Scan stack and free all nodes
		while(top != NULL)
		{
			temp = top;
			top = top->next;
			free(temp);
		}
	}
}

//--------------------------------------------
// Function: Push()
// Purpose: Push an item onto the stack.
// Returns: TRUE if push was successful
//		or FALSE if the push failed.
//--------------------------------------------
int Push(char ch)
{
	struct StackItem *newNode;

	// Create a new node and insert the data
	newNode = (struct StackItem *)malloc(sizeof(struct StackItem));
	// Check to see if memory allocation failed
	if(newNode == NULL) return FALSE;
	// If all OK then insert the data
	newNode->ch = ch;
	newNode->next = NULL; // Very important to init this to NULL

	// Check to see if the stack is empty
	if(isEmpty())
	{
		// Push new node as first in the stack
		top = newNode;
	}
	else
	{
		// Push on top of the stack
		newNode->next = top;
		top = newNode;
	}
	return TRUE; // Signal successful push
}

//--------------------------------------------
// Function: Pop()
// Purpose: Pop an item from the Stack.
// Returns: TRUE if pop was successful
//		or FALSE if the pop failed.
//--------------------------------------------
char Pop()
{
	char ch;
	struct StackItem	*temp;

	// Check for empty stack
	if(isEmpty()) return '\0'; // Return null character if empty

	// Remove the top item from the stack
	temp = top;
	top = top->next;

	// Copy the data from the top item for return
	ch = temp->ch;

	// Free the removed node
	free(temp);

	// Return the popped character
	return ch;
}

//--------------------------------------------
// Function: isEmpty()
// Purpose: Return true if the stack is empty
// Returns: TRUE if empty, otherwise FALSE
// Note: C has no boolean data type so we use
//	the defined int values for TRUE and FALSE
//	instead.
//--------------------------------------------
int isEmpty()
{
	return (top == NULL);
}

//--------------------------------------------
// Function: isFull()
// Purpose: Return true if the stack is full
// Returns: TRUE if full, otherwise FALSE
// Note: In theory a linked stack cannot be
//  full (unless you run out of memory) so
//	this function defaults to returning FALSE.
//--------------------------------------------
int isFull()
{
	return FALSE;
}

Main file used to test the stack
//---------------------------------------------------------------
// File: ListMain.c
// Purpose: Main file with tests for a demonstration of a stack  
//		implemented as a linked structure.
// Programming Language: C
// Author: Dr. Rick Coleman
// Date: January 21, 2002
//---------------------------------------------------------------
#include <stdio.h>
#include "Code126_Stack.h"

int main(int argc, char **argv)
{
	char	testString[51];
	int		i;
	char	ch;

	printf("Simple Stack Demonstration\n");
	printf("(Stack implemented as a linked structure - Stack data type is character.)\n\n");
	printf("Creating a stack\n");

	InitStack();
	printf("Stack created...\n");

	// Test pushing and popping first/last item on a stack
	printf("Testing push and pop of single item.\n");
	Push('A');
	printf("Popped: %c\n", Pop());
	printf("...done\n\n");

	// Test stack by reversing the order of letters in a string
	printf("Enter a string to be reversed (50 characters max)");
	gets(testString); // Assume user is smart enought to not exceed the limit

	// Push all letters on the stack
	i = 0;
	while(testString[i] != '\0')
	{
		Push(testString[i]);
		i++;
	}

	// Pop letters and print in reverse
	printf("Your string printed in reverse is...\n");
	while((ch = Pop()) != '\0') // Pop returns null terminator when stack is empty
		printf("%c", ch);

	printf("\n\n...done.\n");
	return 0;
}