---
# System prepended metadata

title: '[資料結構 stack]'

---

# [資料結構 stack]
* 用array實作

```
//用typedef代表之後可以直接用stack_t來宣告，ex:stack_t
typedef struct stack
{
    int top;
    int maxTop;
    int *data;
}stack_t;

void createStack(stack_t* st, int size)
{
    st->top = -1;
    st->maxTop = size-1;//maxTop代表index
    st->data = (int*)malloc(sizeof(int)*size);
}

bool isFull(stack_t* st)
{
    if(st->top == st->maxTop)
        return true;
    else
        return false;
}

bool isEmpty(stack_t* st)
{
    if(st->top == -1)
        return true;
    else
        return false;
}

int peak(stack_t* st)
{
    if(isEmpty(st))
        printf("noData!");
    else
        return st->data[st->top];
}

void push(stack_t* st, int data)
{
    if(isFull(st))
        printf("Full Data!");
    else
        st->data[++st->top] = data;
}

int pop(stack_t* st)
{
    if(isEmpty(st))
        printf("noData!");
    else
        return st->data[st->top--];
}
```
* 用linked list實作
```
typedef struct stack
{
    int data;
    stack_t* next;
}stack_t

stack_t* head = null;

bool isEmpty()
{
    if(head == null)
        return true;
    else
        return false;
}

stack_t* createNode()
{
    stack_t* tmp = (stack_t*)malloc(sizeof(stack_t));
    return tmp;
}

void push(int data)
{
    stack_t* newNode = createNode();
    newNode->data = data;
    if(isEmpty())
    {
        head = newNode;
        newNode->next = null;
    }
    else
    {
        newNode->next = head;
        head = newNode;
    }
}

int pop()
{
    if(isEmpty())
        printf("noData!");
    else
    {
        stack_t* tmp = head;
        head = head->next;
        return tmp->data;
    }
}

void peak()
{
    f(isEmpty())
        printf("noData!");
    else
        printf("%d", head->data);
}

```