THÔNG TIN CHI TIẾT
Code C\C++: Ví dụ về Stack (sử dụng mảng tĩnh)  Cập nhật :14/12/2013  

/* Ví dụ về xử lý STACK (sử dụng mảng tĩnh)
- tạo stack ngẫu nhiên
- Lấy phần tử ra khỏi stack
*/

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

#define MAX 100

int stack[2*MAX];
int top1, top2;

// khởi tạo stack
void initstack()
{
  top1 = -1;
  top2 = 2*MAX;
}

// đưa phần tử vào stack
void push(int value, int _stack)
{
  if (_stack == 0)
  {
    if (top1<top2)
      stack[++top1] = value;
  }
  else
  {
    if (top1<top2)
      stack[--top2] = value;
  }
}

// kiểm tra stack rỗng
int isempty(int _stack)
{
  if (_stack == 0)
    return top1 == -1;
  else
    return top2 == 2*MAX;
}

// lấy phần tử ra khỏi stack
int pop(int _stack)
{
  if (_stack == 0)
    if (!isempty(_stack))
      return(stack[top1--]);
  if (!isempty(_stack))
    return stack[top2++];
  else
    return -1;
}

// hàm chính
void main()
{

  int i, value, _stack;

  initstack();
  randomize();

  for (i = 0; i<20; i++)
  {
    _stack = random(2);
    value  = random(10); // tạo giá trị ngẫu nhiên
    printf("\nPUSH %d vao stack %d", value, _stack);
    push(value, _stack);
  }

  printf("\nLay nhung gia tri tu stack 0 : ");

  while (!isempty(0))
    printf("%3d", pop(0));

  printf("\nLay nhung gia tri tu stack 1 : ");

  while (!isempty(1))
    printf("%3d", pop(1));

  getch();

}

THÔNG TIN MỚI KHÁC
Những tai nạn "phòng the" có thể khiến bạn mất mạng -12/10/2019
Những sự thật về phương pháp tránh thai phổ biến nhất -28/09/2019
Vì sao đèn xi-nhan lại có màu da cam? -28/09/2019

Chia sẻ đến
THÔNG TIN