Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

แนวคิดของ Stack (สแต็ก) ในภาษา C

โครงสร้างข้อมูล (Data Structure) คือการจัดเก็บข้อมูลอย่างเป็นระบบ แบ่งเป็น 2 ประเภทหลัก:

  • Linear Data Structure - จัดเรียงข้อมูลแบบเส้นตรง เช่น Array, Structure, Stack, Queue, Linked List
  • Non-linear Data Structure - จัดเรียงแบบลำดับชั้น เช่น Tree, Graph, Set, Table

Stack (สแต็ก) คืออะไร?

Stack เป็น Linear Data Structure ที่ข้อมูลถูกเพิ่ม (Insert) และลบ (Remove) ได้ที่ปลายเดียวเท่านั้น เรียกว่าการทำงานแบบ LIFO (Last In First Out) - เข้าสุดท้าย ออกก่อน

การดำเนินการหลัก (Operations)

  • Push - เพิ่มข้อมูลเข้า Stack
  • Pop - นำข้อมูลออกจาก Stack

เงื่อนไขข้อผิดพลาด

  • Stack Overflow - พยายาม Push เข้า Stack ที่เต็มแล้ว
  • Stack Underflow - พยายาม Pop จาก Stack ที่ว่างเปล่า

อัลกอริทึม

Push()

if (top == n-1) 
    printf("Stack Overflow");
else {
    top++;
    a[top] = item;
}

Pop()

if (top == -1)
    printf("Stack Underflow");
else {
    item = a[top];
    top--;
}

Display()

if (top == -1)
    printf("Stack is empty");
else {
    for(i = 0; i <= top; i++)
        printf("%d ", a[i]);
}

ตัวอย่างโปรแกรมครบถ้วน

#include <stdio.h>
#include <stdlib.h>

#define MAX 100
int stack[MAX];
int top = -1;

void push() {
    int item;
    if (top == MAX - 1)
        printf("Stack Overflow\n");
    else {
        printf("Enter element: ");
        scanf("%d", &item);
        stack[++top] = item;
    }
}

void pop() {
    if (top == -1)
        printf("Stack Underflow\n");
    else
        printf("Deleted: %d\n", stack[top--]);
}

void display() {
    if (top == -1)
        printf("Stack is empty\n");
    else {
        for(int i = top; i >= 0; i--)
            printf("%d ", stack[i]);
        printf("\n");
    }
}

int main() {
    int ch;
    while(1) {
        printf("\n1. Push\n2. Pop\n3. Display\n4. Exit\nChoice: ");
        scanf("%d", &ch);
        switch(ch) {
            case 1: push(); break;
            case 2: pop(); break;
            case 3: display(); break;
            case 4: exit(0);
        }
    }
    return 0;
}