Diễn đàn hỏi đáp học thuật - Download Tài Liệu Miễn Phí
Bạn có muốn phản ứng với tin nhắn này? Vui lòng đăng ký diễn đàn trong một vài cú nhấp chuột hoặc đăng nhập để tiếp tục.

Diễn đàn hỏi đáp học thuật - Download Tài Liệu Miễn PhíĐăng Nhập

VỮNG TIN - TIẾP BƯỚC - THÀNH CÔNG


descriptionBài 8. Tổng n phần tử trong Stack EmptyBài 8. Tổng n phần tử trong Stack

more_horiz
BÀI TOÁN
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.

descriptionBài 8. Tổng n phần tử trong Stack EmptyThuật toán tính tổng bằng đệ quy

more_horiz

Code:

ElementType Sum(Stack S) {
    Stack temp = S->Next;
    if(temp==NULL)
        return 0;
    else
        return temp->Element+Sum(temp);
}
privacy_tip Permissions in this forum:
Bạn không có quyền trả lời bài viết
power_settings_newLogin to reply