Skip to content

Instantly share code, notes, and snippets.

@hiepph
Last active September 29, 2015 14:04
Show Gist options
  • Save hiepph/d383fdba82f6961f8651 to your computer and use it in GitHub Desktop.
Save hiepph/d383fdba82f6961f8651 to your computer and use it in GitHub Desktop.
Stack Implementation using Single Linked List
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "stack_list.h"
stack_t *Initialize()
{
stack_t *top = NULL;
return top;
}
int Empty(stack_t *top)
{
return top == NULL;
}
void Push(stack_t **top, data_t data)
{
// create new stack's node
stack_t *NewNode = (stack_t*)malloc(sizeof(stack_t));
assert(NewNode != NULL);
NewNode->data = data;
// push into stack and make new top
NewNode->next = *top;
*top = NewNode;
}
stack_t *Pop(stack_t **top, data_t *save)
{
if(Empty(*top)) {
printf("ERROR: Stack is empty. Can't pop.\n");
return NULL;
}
// save the data
*save = (**top).data;
stack_t *temp = *top;
*top = (**top).next;
free(temp);
return *top;
}
#ifndef STACK_LIST_H
#define STACK_LIST_H
typedef ... data_t;
typedef struct StackNode {
data_t data;
struct StackNode *next;
} stack_t;
stack_t *Initialize();
int Empty(stack_t *top);
void Push(stack_t **top, data_t data);
stack_t *Pop(stack_t **top, data_t *save);
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment