用链表实现集合

用链表来表示集合时,链表的中的每个项表示集合的一个成员,表示集合的链表所占用的空间正比于所表示的集合的大小,而不是正比于全集合的大小,因此,链表可以表示无穷全集合的子集。

链表分为无序链表和有序链表两种类型。

以下为有序链表实现代码:

 1 typedef struct node *link;
 2 struct node
 3 {
 4     int data;//有序链表的结点类型Node
 5     link next;
 6 }Node;
 7 
 8 typedef struct list *Set;
 9 struct list 
10 {
11     link first;//指向第一个元素的指针
12 }LIst;
13 
14 //建立一个空集合
15 Set SetInit()
16 {
17     Set S=malloc(sizeof*S);
18     S->first=0;
19     return S;
20 }
21 
22 //判断集合S是否为空
23 int SetEmpty(Set S)
24 {
25     return S->first==0;
26 }
27 
28 //返回集合S的大小
29 int SetSize(Set S)
30 {
31     int len;
32     link current;
33     current=S->first;
34     len=0;
35     while(current!=NULL)
36     {
37         len++;
38         current=current->next;
39     }
40 }
41 
42 //实现交集运算
43 Set SetIntersection(Set A,Set B)
44 {
45     link a,b,p,q,r;
46     Set tmp=SetInit();
47     a=A->first;
48     b=B->first;
49     p=(link)malloc(sizeof(Node));
50     q=p;
51     while(a&&b)
52     {
53         if(a->data==b->data)
54         {
55             r=(link)malloc(sizeof(Node));
56             r->data=a->data;
57             r->next=0;
58             p->next=r;
59             p=r;
60             a=a->next;
61             b=b->next;
62         }
63         else if(a->data<b->data)
64             a=a->next;
65         else
66             b=b->next;
67     }
68     if(p!=q)
69         tmp->first=q->next;
70     return tmp;
71 }
72 //插入元素x
73 void SetInsert(int x,Set S)
74 {
75     link p,q,r;
76     p=S->first;
77     q=p;
78     while(p&&p->data<x)//找插入结点位置
79     {
80         q=p;
81         p=p->next;
82     }
83     if(p&&p->data==x)
84         return ;
85     r=(link)malloc(sizeof(Node));
86     r->data=x;
87     r->next=0;
88     if(p==q)//恰好在头结点
89         S->first=r;
90     else
91         q->next=r;
92 
93 
94 }
View Code

 

posted @ 2013-11-07 22:58  陈泽泽  阅读(1162)  评论(0编辑  收藏  举报