BÀI TOÁN
HÀM TÌM KIẾM (tìm thấy trả về giá trị 1 ngược lại 0)
CHƯƠNG TRÌNH MẪU
Cho Stack gồm n phần tử được nhập từ bàn phím. Thực hiện việc kiểm tra phần tử x có tồn tại trong Stack hay không?
HÀM TÌM KIẾM (tìm thấy trả về giá trị 1 ngược lại 0)
Code:
char Test(Stack S, ElementType x) {
Stack temp = S->Next;
while(temp!=NULL)
{
if(temp->Element==x)
return 1;
temp = temp->Next;
}
return 0;
}
CHƯƠNG TRÌNH MẪU
Code:
#include "conio.h"
#include "stdio.h"
#include "alloc.h"
typedef int ElementType;
typedef struct Node{
ElementType Element;
Node * Next;
};
typedef Node * Stack;
Node * Make_Node(ElementType x) {
Node * temp = (Node*)malloc(sizeof(Node));
temp->Element = x;
return temp;
}
Stack MakeNull_Stack() {
Stack temp = (Stack)malloc(sizeof(Stack));
temp->Next = NULL;
return temp;
}
char Empty_Stack(Stack S) {
return S->Next==NULL;
}
void Push(Stack S, ElementType x) {
Node * p = Make_Node(x);
p->Next = S->Next;
S->Next = p;
}
void Out_Stack(Stack S) {
Stack temp = S->Next;
while(temp!=NULL) {
printf("%d\t",temp->Element);
temp = temp->Next;
}
}
Stack Input_Stack(unsigned int n) {
Stack temp = MakeNull_Stack();
unsigned int i = 0;
ElementType x;
while(i<n)
{
printf("Elemnet %d = ",i);
scanf("%d",&x);
Push(temp,x);
i++;
}
return temp;
}
char Test(Stack S, ElementType x) {
Stack temp = S->Next;
while(temp!=NULL)
{
if(temp->Element==x)
return 1;
temp = temp->Next;
}
return 0;
}
void main() {
clrscr();
unsigned int n;
ElementType x;
printf("n = ");
scanf("%d",&n);
Stack S = Input_Stack(n);
printf("This stack:\n");
Out_Stack(S);
printf("\nInput a value to find: ");
scanf("%d",&x);
if(Test(S,x))
printf("This value has in Stack!");
else
printf("This value don't have in Stack");
getch();
}