// C program for linked list implementation of stack
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
// A structure to represent a stack
struct StackNode
{
int data;
struct StackNode* next;
};
struct StackNode* newNode(int data)
{
struct StackNode* stackNode = (struct StackNode*) malloc(sizeof(struct StackNode));
stackNode->data = data;
stackNode->next = NULL;
return stackNode;
}
int isEmpty(struct StackNode *root)
{
return !root;
}
void push(struct StackNode** root, int data)
{
struct StackNode* stackNode = newNode(data);
/*
* 將新node的下一個node指向array[0]
*/
stackNode->next = root[0];
/*
* 將新node的值assign給array[0]
*/
root[0] = stackNode;
printf("%d pushed to stack\n", data);
}
int pop(struct StackNode** root)
{
/*
* 如果array沒有node, 回傳INT_MIN
*/
if (isEmpty(root[0]))
return INT_MIN;
/*
* 新增一個temp node, 並將array[0]的值assign給temp node
*/
struct StackNode* temp = root[0];
/*
* 將array[0]下一個node的值assign給array[0]
*/
root[0] = (root[0])->next;
/*
* 回傳原array[0]的data
*/
int popped = temp->data;
free(temp);
return popped;
}
int peek(struct StackNode* root)
{
if (isEmpty(root))
return INT_MIN;
return root->data;
}
int main()
{
struct StackNode* root = NULL;
push(&root, 10);
push(&root, 20);
push(&root, 30);
printf("%d popped from stack\n", pop(&root));
printf("Top element is %d\n", peek(root));
return 0;
}