Monday, June 20, 2016

Lập trình hướng đối tượng với C++ (Giải đề thi ngày 21/06/2016)

//Họ và tên: Trần Văn Linh

//Msv: 581597

//Lớp: K58QLTT

//Đề 29 Bài 2:Nhập vào 1 dãy n số nguyên, lưu trữ trong một hàng đợi. Đưa ra dãy số nguyên ra màn hình theo đúng thứ tự đã nhập. Tính tổng các số nguyên dương. Yêu cầu trong chương trình có sử dụng hàng đợi lưu trữ bằng danh sách liên kết đơn


#include<iostream>
using namespace std;
//khai bao lop
class DSLKD
{
          private:
                   struct node
                   {
                             int info;
                             node *link;
                   } *F,*R;
          public:
                   DSLKD();
                   ~DSLKD();
                   void cqinsert(int x);
                   int cqdelete();
                   int empty();
};
//==chuong trinh chinh
int main()
{
          DSLKD ds;
          int n;
          cout<<"Nhap so luong so nguyen: ";
          cin>>n;
          int x;
          for(int i=0;i<n;i++)
          {
                   cout<<"Nhap so nguyen: ";
                   cin>>x;
                   if(x>0)
                             ds.cqinsert(x);
          }
          int tong=0;
          cout<<"Cac so nguyen duong da nhap: ";
          while(!ds.empty())
          {
                   int tg=ds.cqdelete();
                   tong=tong+tg;
                   cout<<tg<<"  ";
          }
          cout<<"\nTong cac so nguyen duong da nhap: "<<tong<<endl;
          return 0;
}
//==dinh nghia ham
DSLKD::DSLKD():F(NULL),R(NULL)
{
                  
}
DSLKD::~DSLKD()
{
          node *P;
          if(F==R)
          {
                   delete F;
                   delete R;
          }
          while(F)
          {
                   P=F;
                   F=F->link;
                   delete P;
          }                 
}
//--------------
void DSLKD::cqinsert(int x)
{
          node *N;
          N=new node;
          N->info=x;
          N->link=NULL;
          if(R==NULL)
                   R=F=N;
          else
          {
                   R->link=N;
                   R=N;
          }
}
//--------------
int DSLKD::cqdelete()
{
          if(F==NULL)
          {
                   return 0;
          }
          int y=F->info;
          node *P;
          P=F;
          F=F->link;
          delete P;
          return y;
}
//--------------
int DSLKD::empty()
{
          if(F==NULL)
                   return 1;
          return 0;
}

//--------------
Kết quả khi chạy thử :



0 comments:

Post a Comment