Understanding Stack Data Structure: Sequential and Linked Implementations

Sequential Stack

A sequential stack uses an array with a top pointer to track the top element.

Stack Structure

typedef struct {
    int items[MAXLEN];
    int topIndex;
} SeqStack;

Initialize Stack

void CreateSeqStack(SeqStack *stack) {
    stack->topIndex = -1;
}

Check If Empty

int IsEmptySeq(SeqStack *stack) {
    return stack->topIndex == -1;
}

Check If Full

int IsFullSeq(SeqStack *stack) {
    return stack->topIndex == MAXLEN - 1;
}

Push Operation

int PushSeq(SeqStack *stack, elemType value) {
    if (IsFullSeq(stack)) {
        printf("Stack overflow\n");
        return 0;
    }
    stack->items[++stack->topIndex] = value;
    return 1;
}

Pop Operatoin

elemType PopSeq(SeqStack *stack) {
    if (IsEmptySeq(stack)) {
        printf("Stack underflow\n");
        exit(EXIT_FAILURE);
    }
    return stack->items[stack->topIndex--];
}

Peek Top Element

elemType PeekSeq(SeqStack *stack) {
    if (IsEmptySeq(stack)) {
        printf("Stack is empty\n");
        exit(EXIT_FAILURE);
    }
    return stack->items[stack->topIndex];
}

Linked Stack

A linked stack implements the stack using a singly linked list, where the head node represents the top of the stack.

Node Structure

typedef struct StackNode {
    elemType data;
    struct StackNode *next;
} StackNode;

typedef StackNode *LinkStack;

Check If Empty

int IsEmptyLink(LinkStack head) {
    return head == NULL;
}

Push Operation

LinkStack PushLink(LinkStack head, elemType val) {
    StackNode *node = (StackNode *)malloc(sizeof(StackNode));
    node->data = val;
    node->next = head;
    return node;
}

Pop Operation

LinkStack PopLink(LinkStack head, elemType *val) {
    if (IsEmptyLink(head)) {
        printf("Stack is empty\n");
        exit(EXIT_FAILURE);
    }
    *val = head->data;
    LinkStack temp = head;
    head = head->next;
    free(temp);
    return head;
}

Peek Top Element

elemType PeekLink(LinkStack head) {
    if (IsEmptyLink(head)) {
        printf("Stack is empty\n");
        exit(EXIT_FAILURE);
    }
    return head->data;
}

Comparision

Aspect Sequential Stack Linked Stack
Memory Fixed size, pre-allocated Dynamic size, allocated on demand
Push O(1) with overflow check O(1)
Pop O(1) O(1)
Memory Waste May have unused slots No waste
Overflow Fixed capacity limitaiton No overflow (memory permitting)

Tags: data structure stack sequential stack linked stack algorithm

Posted on Sat, 03 Oct 2026 16:50:32 +0000 by pob123