BÀI TOÁN
HÀM TÍNH TỔNG
CHƯƠNG TRÌNH MẪU
Được sửa bởi Admin ngày Wed Oct 20, 2010 4:29 pm; sửa lần 1.
Sử dụng Stack nhập n số nguyên tù bàn phím và tính tổng n số nguyên vừa nhập.
HÀM TÍNH TỔNG
Code:
ElementType Sum(Stack S) {
ElementType temp = 0;
Stack p = S->Next;
while(p!=NULL)
{
temp+=p->Element;
p = p->Next;
}
return temp;
}
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 = 1;
ElementType x;
while(i<=n)
{
printf("Elemnet %d = ",i);
scanf("%d",&x);
Push(temp,x);
i++;
}
return temp;
}
ElementType Sum(Stack S) {
ElementType temp = 0;
Stack p = S->Next;
while(p!=NULL)
{
temp+=p->Element;
p = p->Next;
}
return temp;
}
void main() {
clrscr();
unsigned int n;
printf("n = ");
scanf("%d",&n);
Stack S = Input_Stack(n);
printf("This stack:\n");
Out_Stack(S);
printf("\nSum of all values in Stack: %d", Sum(S));
getch();
}
Được sửa bởi Admin ngày Wed Oct 20, 2010 4:29 pm; sửa lần 1.