《数据结构教程》(李春葆 主编)课后习题【练习题6】

【6.5】

 1 #include <iostream>
 2 
 3 using namespace std;
 4 #define MAXN 100
 5 #define N 4
 6 #define M 4
 7 int x,y,num;
 8 int a[MAXN][MAXN] = {
 9     {0,2,3,4},
10     {1,5,6,7},
11     {8,9,10,11},
12     {12,13,14,15}};
13 bool FindX(int X)
14 {
15     while(a[x][y]!=X){
16         if(a[x][y]<X)
17             x++;
18         else
19             y--;
20         num++;
21         if(x<0 || x>=M || y<0 || y>=N)  //如果要查找的位置越界,说明没找到
22             return false;
23     }
24     return true;
25 }
26 int main()
27 {
28     int X;
29     while(cin>>X){
30         num=0;
31         x=0,y=N-1;
32         if(FindX(X)){
33             cout<<"找到x,位置在"<<'('<<x<<','<<y<<')'<<endl;
34             cout<<"比较了"<<num<<""<<endl;
35         }
36         else{
37             cout<<"查找失败"<<endl;
38         }
39     }
40     return 0;
41 }

【6.6】

 1 #include <iostream>
 2 
 3 using namespace std;
 4 #define M 4
 5 #define N 4
 6 #define MAXSIZE M*N
 7 typedef struct{
 8     int r;  //行号
 9     int c;  //列号
10     int d;  //元素值
11 }TupNode;   //三元组定义
12 typedef struct{
13     int rows;   //行数
14     int cols;   //列数
15     int nums;   //非0元素数
16     TupNode data[MAXSIZE];
17 }TSMatrix;  //三元组顺序表定义
18 int GetSum(TSMatrix ts) //返回三元组表对角线上元素和
19 {
20     int i,sum=0;
21     for(i=0;i<ts.nums;i++){
22         if(ts.data[i].c==ts.data[i].r)
23             sum+=ts.data[i].d;
24     }
25     return sum;
26 }
27 int main()
28 {
29     int Case=1,nums,i,r,c,d;
30     cout<<"* 该三元组大小为"<<M<<'*'<<N<<",可在宏定义中修改"<<endl<<endl;
31     cout<<"#Case "<<Case++<<':'<<endl;
32     cout<<"请输入三元组表存储的非0元素的数量:"<<endl;
33     while(cin>>nums){
34         if(nums==0) break;   //输入为0结束
35         TSMatrix ts;
36         ts.rows = M;    //确定三元组表的行数,列数
37         ts.cols = N;
38         ts.nums = nums;
39         for(i=0;i<ts.nums;i++){ //依次输入这nums个非0元素
40             cout<<"请输入第"<<i+1<<"个非0数的行号,列号和元素值"<<endl;
41             cin>>r>>c>>d;  //分别输入行号,列号,元素值
42             if(r<0 || r>=M || c<0 || c>=N){ //越界
43                 cout<<"输入错误,请重新输入该元素"<<endl;
44                 i--;
45             }
46             else{   //没有越界
47                 ts.data[i].r = r;
48                 ts.data[i].c = c;
49                 ts.data[i].d = d;
50             }
51         }
52         cout<<"对角线上元素和为 "<<GetSum(ts)<<endl<<endl;
53         cout<<"#Case "<<Case++<<':'<<endl;
54         cout<<"请输入三元组表存储的非0元素的数量:"<<endl;
55     }
56     return 0;
57 }


Freecode : www.cnblogs.com/yym2013

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值