稀疏矩阵
#include<iostream>
using namespace std
;
typedef int datatype
;
#define smax 100
typedef struct
{
int i
, j
;
datatype v
;
}node
;
typedef struct
{
int m
, n
, t
;
node data
[smax
];
}spmatrix
;
spmatrix
*creat()
{
int m
, n
, t
,i
,j
;
datatype v
;
spmatrix
*p
;
p
=(spmatrix
*)malloc(sizeof(spmatrix
));
cout
<< "please input lines and cols and element number:" << endl
;
cin
>> m
>> n
>> t
;
p
->m
= m
;p
->n
= n
;p
->t
= t
;
cout
<< "please input element(cols number 、lines number、data ):" << endl
;
for (int x
= 0;x
< t
;x
++)
{
cin
>> i
>> j
>> v
;
if (i
> m
|| j
> n
) { cout
<< "have error." << endl
;return NULL; }
p
->data
[x
].i
= i
;p
->data
[x
].j
= j
;p
->data
[x
].v
= v
;
}
return p
;
}
void display(spmatrix
*p
)
{
int m
,n
;
int t1
= 0;
m
= p
->m
;n
= p
->n
;
for (int x
= 0;x
< m
;x
++)
{
for(int x1
=0;x1
<n
;x1
++)
{
if (x
== p
->data
[t1
].i
&& x1
==p
->data
[t1
].j
) { cout
<< p
->data
[t1
].v
<< " ";++t1
; }
else { cout
<< 0 << " "; }
}
cout
<< endl
;
}
}
spmatrix
transmat(spmatrix
*a
)
{
spmatrix
*b
;
b
=(spmatrix
*) malloc(sizeof(spmatrix
));
int m
, n
, t
,bno
=0;
m
= a
->m
;n
= a
->n
;t
= a
->t
;
b
->m
= n
;b
->n
= m
;b
->t
= t
;
for (int i
= 0;i
< m
;i
++)
{
for (int t1
= 0;t1
<a
->t
;t1
++)
{
if ((i
== (a
->data
[t1
].i
-1)))
{
b
->data
[bno
].j
= a
->data
[t1
].i
;
b
->data
[bno
].i
= a
->data
[t1
].j
;
b
->data
[bno
].v
= a
->data
[t1
].v
;
bno
++;
}
}
}
return *b
;
}
int main()
{
spmatrix
*p
;
p
= creat();
display(p
);
return 0;
}
十字链表发
#include<iostream>
using namespace std
;
typedef int datatype
;
#define smax 100
typedef struct Inode
{
int i
, j
;
struct Inode
*cptr
, *rptr
;
union
{
struct Inode
*next
;
datatype v
;
}uval
;
}link
;
link
*creatlinkmat()
{
link
*p
, *q
, *L
, *cp
[smax
];
int i
, j
, m
, n
, t
, s
;
datatype v
;
cout
<< "please input lines and cols and element: " << endl
;
cin
>> m
>> n
>> t
;
if (m
> n
)s
= m
;
else s
= n
;
L
= (link
*)malloc(sizeof(link
));
L
->i
= m
;L
->j
= n
;
cp
[0] = L
;
for (i
= 1;i
<= s
;i
++)
{
p
= (link
*)malloc(sizeof(link
));
p
->i
= 0;p
->j
= 0;
p
->rptr
= p
;
p
->cptr
= p
;
cp
[i
] = p
;
cp
[i
-1]->uval
.next
= p
;
}
cp
[s
]->uval
.next
= L
;
for (i
= 1;i
<= t
;i
++)
{
cin
>> i
>> j
>> v
;
p
= (link
*)malloc(sizeof(link
));
p
->i
= i
;p
->j
= j
;p
->uval
.v
= v
;
q
= cp
[i
];
while ((q
->rptr
!= cp
[i
]) && (q
->rptr
->j
< j
))q
= q
->rptr
;
p
->rptr
= q
->rptr
;
q
= cp
[j
];
while ((q
->cptr
!= cp
[j
]) && (q
->cptr
->i
< i
))q
= q
->cptr
;
p
->cptr
= q
->cptr
;
q
->cptr
= p
;
}
return L
;
}
void main()
{
link k
;
k
= *creatlinkmat();
}
转载请注明原文地址: https://www.6miu.com/read-4931794.html