Design Pattern Examples
Overview of object-oriented design patterns
stack.c
Go to the documentation of this file.
1
5
6#include <stdlib.h>
7
8#include "stack.h"
9
16static StackEntry* StackEntry_Create(void* item)
17{
18 StackEntry* entry = calloc(1, sizeof(StackEntry));
19 if (entry != NULL)
20 {
21 entry->item = item;
22 }
23
24 return entry;
25}
26
32static void StackEntry_Destroy(StackEntry* entry)
33{
34 free(entry);
35}
36
38// Stack_Push()
40void Stack_Push(StackEntry** stack, void* item)
41{
42 if (stack != NULL && item != NULL)
43 {
44 StackEntry* entry = StackEntry_Create(item);
45 if (entry != NULL)
46 {
47 if (*stack != NULL)
48 {
49 entry->next = *stack;
50 *stack = entry;
51 }
52 else
53 {
54 *stack = entry;
55 }
56 }
57 }
58}
59
61// Stack_Pop()
63void* Stack_Pop(StackEntry** stack)
64{
65 void* item = NULL;
66 if (stack != NULL)
67 {
68 StackEntry* entry = *stack;
69 if (entry != NULL)
70 {
71 item = entry->item;
72 *stack = entry->next;
73 StackEntry_Destroy(entry);
74 }
75 }
76 return item;
77}
78
80// Stack_IsEmpty()
83{
84 return stack == NULL || *stack == NULL;
85}
static StackEntry * StackEntry_Create(void *item)
Create a new StackEntry object with the given item.
Definition: stack.c:16
bool Stack_IsEmpty(StackEntry **stack)
Determines if the given stack is empty.
Definition: stack.c:82
void Stack_Push(StackEntry **stack, void *item)
Push the given entry onto the given stack.
Definition: stack.c:40
static void StackEntry_Destroy(StackEntry *entry)
Destroys the specified StackEntry object. After this function returns, the object is no longer valid.
Definition: stack.c:32
void * Stack_Pop(StackEntry **stack)
Pop the last entry from the given stack, returning the item.
Definition: stack.c:63
Declaration of the StackEntry structure and the supporting functions that represents a simple stack.
Represents an entry on a simple stack that wraps an "item" represented by an opaque pointer.
Definition: stack.h:32
struct StackEntry * next
Points to the next older entry in the stack.
Definition: stack.h:33
void * item
The item being held in this entry in the stack.
Definition: stack.h:34