#include <stdio.h>
#include <malloc.h>
typedef int ElemType;
typedef struct NODE{
int i;//非零元行号
int j;//非零元列号
ElemType e;//非零元
struct NODE* rptr;//行指针
struct NODE* cptr;//列指针
}Node,*pNode;
typedef struct NODELIST{
int col;//矩阵列数
int row;//矩阵行数
int num;//非零元个数
pNode *rhead;//矩阵行指针
pNode *chead;//矩阵列指针
}List,*pList;
pList Init();//初始化数据
void Insert(pList L);//插入节点数据
void Ptint1(pList L);//按行打印非零元
void Ptint2(pList L);//按列打印非零元
void Destroy(pList L);//释放十字链表空间
int main()
{
pList L = Init();
int count = 1;
while (count <= L->num)
{
Insert(L);
count++;
}
puts("按行打印三元组");
Ptint1(L);
puts("按列打印三元组");
Ptint2(L);
Destroy(L);
system("pause");
return 0;
}
pList Init()
{
pList L = (pList)malloc(sizeof(List));
puts("请输入矩阵的行数,列数,非零元个数");
scanf("%d %d %d", &L->row, &L->col, &L->num);
L->rhead = (pNode)malloc(sizeof(Node) * L->row);
L->chead = (pNode)malloc(sizeof(Node) * L->col);
memset(L->rhead, NULL, sizeof(Node) * L->row);//初始化行头指针
memset(L->chead, NULL, sizeof(Node) * L->col);//初始化列头指针
return L;
}
void Insert(pList L)
{
puts("请输入三元组,非零元的行,列以及非零元的值");
pNode newnode = (pNode)malloc(sizeof(Node));
scanf("%d %d %d", &newnode->i, &newnode->j, &newnode->e);
//按行插入
if (L->rhead[newnode->i - 1] == NULL || newnode->j < L->rhead[newnode->i - 1]->j)
{
newnode->rptr = L->rhead[newnode->i - 1];
L->rhead[newnode->i - 1] = newnode;
}
else
{
pNode temp1 = L->rhead[newnode->i - 1];
pNode temp2 = temp1->rptr;
while (temp2 != NULL)
{
if (newnode->j < temp2->j)
{
break;
}
temp1 = temp2;
temp2 = temp2->rptr;
}
newnode->rptr = temp2;
temp1->rptr = newnode;
}
//printf("%d", L->rhead[newnode->j - 1]->i);
//system("pause");
if (L->chead[newnode->j - 1] == NULL || newnode->i < L->chead[newnode->j - 1]->i)
{
newnode->cptr = L->chead[newnode->j - 1];
L->chead[newnode->j - 1] = newnode;
}
else
{
pNode temp1 = L->chead[newnode->j - 1];
pNode temp2 = temp1->cptr;
while (temp2 != NULL)
{
if (newnode->i < temp2->i)
{
break;
}
temp1 = temp2;
temp2 = temp2->cptr;
}
newnode->cptr = temp2;
temp1->cptr = newnode;
}
}
void Ptint1(pList L)
{
for (int i = 0; i < L->row; i++)
{
pNode temp = L->rhead[i];
while (temp != NULL)
{
printf("%d %d %d\n", temp->i, temp->j, temp->e);
temp = temp->rptr;
}
}
}
void Ptint2(pList L)
{
for (int i = 0; i < L->col; i++)
{
pNode temp = L->chead[i];
while (temp != NULL)
{
printf("%d %d %d\n", temp->i, temp->j, temp->e);
temp = temp->cptr;
}
}
}
void Destroy(pList L)
{
for (int i = 0; i < L->row; i++)
{
pNode temp = L->rhead[i];
pNode freenode;
while (temp != NULL)
{
freenode = temp;
temp = temp->rptr;
free(freenode);
}
}
free(L->rhead);
free(L->chead);
}