C语言-用单链表实现集合
Posted li_Jiejun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C语言-用单链表实现集合相关的知识,希望对你有一定的参考价值。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//单链表结构体表示集合set
typedef struct Link {
char *data;
struct Link *next;
} set;
//带头节点的单链表
set *initSet()
{
set *p;
if((p = (set *)malloc(sizeof(set))) == NULL) {
printf("Error: initSet: malloc failed!\\n");
return NULL;
}
p->next = NULL;
return p;
}
//默认每次都是头部添加
int addSet(set *l, char *value)
{
set *p;
int len;
if((p = (set *)malloc(sizeof(set))) == NULL) {
printf("Error: addSet: malloc failed!\\n");
return 0;
}
while(l->next) {
if(0 == strcmp(value, l->next->data)) {
printf("Error: addSet: %s - already in set, duplicate add!\\n", value);
free(p);
return 0;
}
l = l->next;
}
p->data = value;
p->next = l->next;
l->next = p;
return 1;
}
int delSet(set *l, char *value)
{
set *p = l;
while(p->next) {
if(0 == strcmp(value, p->next->data)) {
set *temp = p->next;
p->next = p->next->next;
free(temp);
return 1;
}
p = p->next;
}
printf("Warn: delSet: not found - %s - in set!\\n", value);
return 0;
}
int updateSet(set *l, char *oldValue, char *newValue)
{
set *p = l;
while(p->next) {
if(0 == strcmp(oldValue, p->next->data)) {
p->next->data = newValue;
return 1;
}
p = p->next;
}
printf("Warn: updateSet: not found - %s - in set!\\n", oldValue);
return 0;
}
int findSet(set *l, char *value)
{
set *p = l;
while(p->next) {
if(0 == strcmp(value, p->next->data)) {
printf("Info: findSet: found - %s - in set!\\n", value);
return 1;
}
p = p->next;
}
printf("Warn: findSet: not found - %s - in set!\\n", value);
return 0;
}
//debug func
void displaySet(set *l) {
set *p = l->next;
while (p!=NULL) {
printf("--%s--\\n", p->data);
p = p->next;
}
}
//使用单链表实现集合
//要求:
// add - 参数 (set,value),value表示要增加的元素值,需要做去重
// del - 参数 (set,value),value表示要删除的元素值
// modify - 参数(set,oldValue, newValue),将集合内oldValue的值修改为newValue
// find - 参数 (set, value),查找集合内是否存在元素value
int main() {
set *p;
int ret = 0;
printf("------init-------\\n");
p = initSet(); //初始化一个空集合
displaySet(p);
printf("\\n");
printf("-------add-------\\n");
ret = addSet(p, "asdf0");
ret = addSet(p, "asdf1");
ret = addSet(p, "asdf2");
ret = addSet(p, "asdf3");
displaySet(p);
ret = addSet(p, "asdf1");
printf("\\n");
printf("\\n");
displaySet(p);
printf("-------del---asdf2----\\n");
ret = delSet(p, "asdf2");
printf("\\n");
printf("\\n");
displaySet(p);
printf("-------update---asdf2/3-->22/33--\\n");
ret = updateSet(p, "asdf2", "asdf22");
ret = updateSet(p, "asdf3", "asdf33");
printf("\\n");
printf("\\n");
displaySet(p);
printf("-------find---asdf100/1----\\n");
ret = findSet(p, "asdf100");
ret = findSet(p, "asdf1");
// displaySet(p);
return 0;
}
以上是关于C语言-用单链表实现集合的主要内容,如果未能解决你的问题,请参考以下文章