Em chào mọi người, em đang học c# và cấu trúc dữ liệu stack . Trong bước cài đặt Stack bằng Array có một số lỗi logic chạy nhưng không thành công nhờ mọi người chỉ giáo ạ. Em cảm ơn
public struct Stack //khởi tạo stack
{
public int[] data;
public int top;
}
class Program
{
public static Boolean IsFull(Stack S) //kiểm tra stack đầy hay không
{
if (S.top == S.data.Length-1) //vị trí top so với chiều dài của mảng - 1
{
return true;
}
else
{
return false;
}
}
public static Boolean IsEmpty(Stack S) //kiểm tra stack có trống hay không
{
if(S.top == -1) //top bằng giá trị ban đầu = -1
{
return true;
}
else
{
return false;
}
}
public static void Push(Stack S, int x) //đẩy phần tử vào stack
{
if (IsFull(S) == false) //kiểm tra stack có đầy hay không
{
S.top++; //tăng top lên 1
S.data[S.top] = x; //gán x vào vị trí top
}
else
{
Console.WriteLine("Stack Overflow");
}
}
public static void Pop(Stack S) //lấy phần tử
{
if (IsEmpty(S) == false) //kiểm tra stack có trống hay không?
{
S.top--; //giảm top đi 1
}
else
{
Console.WriteLine("Stack Underflow");
}
}
public static void Peek(Stack S) //lấy giá trị top
{
if (IsEmpty(S) == false) //kiểm tra stack có trống hay không
{
Console.WriteLine("Top Element: " + S.data[S.top]);
}
else
{
Console.WriteLine("Stack Underflow");
}
}
public static void NumberElement(Stack S)//xuất các phần tử có trong stack
{
string str = " ";
for(int i = S.top; i >= 0; i--) //gán i từ top đến 0
{
str += S.data[i] + " ";
}
Console.WriteLine("Element: " + str);
}
public static void Main(string[] args) //hàm main
{
Stack S = new Stack(); //khai báo stack
S.data = new int[3]; //tạo mảng
S.top = -1; //gán top = -1
Console.WriteLine("==========================");
Console.WriteLine("|1. Push |");
Console.WriteLine("|2. Pop |");
Console.WriteLine("|3. Show Top Element |");
Console.WriteLine("|4. Show Elements in Stack|");
Console.WriteLine("==========================");
int numC;
do
{
Console.WriteLine("Choose Option");
numC = int.Parse(Console.ReadLine());
switch (numC)
{
case 1:
Console.WriteLine("Input Number: ");
int x = int.Parse(Console.ReadLine());
Push(S, x);
break;
case 2:
Pop(S);
break;
case 3:
Peek(S);
break;
case 4:
NumberElement(S);
break;
}
}
while (numC < 5);
}
}