#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_TREE_SIZE 100
#define OVERFLOW -1
#define OK 1
#define ERROR -1
#define TRUE 1
#define FALSE 0
typedef int Status;
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode* next;
}LNode, * LinkList;
Status InitList(LinkList L)
{
L->next = NULL;
return OK;
}
int ListLength(LinkList L)
{
int i = 0;
LNode* p = L->next;
while (p)
{
i++;
p = p->next;
}
return i;
}
Status ListInsert(LinkList L, int i, ElemType e)
{
int len = ListLength(L);
if (i <= 0 || i > len + 1)
return ERROR;
LNode* p;
p = (LinkList)malloc(sizeof(LNode));
if (!p) exit(OVERFLOW);
p->data = e;
LNode* q = L;
int j = 1;
while (j < i)
{
q = q->next;
j++;
}
p->next = q->next;
q->next = p;
return OK;
}
Status ListDelete(LinkList L, int i)
{
int len = ListLength(L);
if (i < 1 || i > len)
return ERROR;
int j = 1;
LNode* p = L;
while (j < i)
{
p = p->next;
j++;
}
LNode* q = p->next;
p->next = q->next;
free(q);
return OK;
}
Status GetElem(LinkList L, int i, ElemType* e)
{
int len = ListLength(L);
if (i <= 0 || i > len)
return ERROR;
LNode* p = L;
int j = 0;
while (j < i)
{
p = p->next;
j++;
}
*e = p->data;
return OK;
}
void GetPowerSet(int i, LinkList L1, LinkList L2)
{
if (i > ListLength(L1))
{
LNode* p = L2->next;
if(p)
{
while (p)
{
printf("%d", p->data);
p = p->next;
}
}
else
{
printf("空集");
}
printf("\n");
}
else
{
ElemType e;
GetElem(L1, i, &e);
int len = ListLength(L2);
ListInsert(L2, len + 1, e);
GetPowerSet(i + 1, L1, L2);
ListDelete(L2, len + 1);
GetPowerSet(i + 1, L1, L2);
}
}
主函数:
int main()
{
LinkList L1, L2;
L1 = (LinkList)malloc(sizeof(LNode));
if (!L1) exit(OVERFLOW);
L2 = (LinkList)malloc(sizeof(LNode));
if (!L2) exit(OVERFLOW);
InitList(L1);
InitList(L2);
ListInsert(L1, 1, 3);
ListInsert(L1, 2, 5);
ListInsert(L1, 3, 8); //集合为{3,5,8}
GetPowerSet(1, L1, L2);
return 0;
}
结果: