动态集合:集合可以增大、缩小或随时间而变化。
动态集合上的操作可分为两类:
1.查询,返回有关集合的信息;
2.修改:对集合有所改变。
Search(S, k):给定一个集合S和关键字k,返回一个指向S中元素的指针x,使key[x] = k,或当S中不存在这样的元素时返回NULL。
Insert(S, x):将由x指向的元素增加到S中去,通常假定x中的域都已被初始化。
Delete(S, x):当给定一个指向S中元素的指针x时,将x从S中去掉。
Minimum(S):是个全序集S上的查询,返回S中具有最小关键字的元素。
Maximum(S):是个全序集S上的查询,返回S中具有最大关键字的元素。
Successor(S, x):给定关键字属于全序集S上的某个元素x,返回S中比x大的下一个元素;当x为最大元素时,返回NULL。
Predecessor(S, x):给定关键字属于全序集S上的某个元素x,返回S中比x小的前一个元素;当x为最小元素时,返回NULL。
基本数据结构——栈
stack.h
#ifndef _STACK_H
#define _STACK_H
typedef
int ElemType;
#define StackInitSize 100
#define StackIncrement 10

typedef
struct SqStack...{
ElemType
*base;
ElemType
*top;
int stacksize;
}Stack;
int InitStack(Stack
**s);
int DestroyStack(Stack
**s);
int ClearStack(Stack
**s);
int StackEmpty(Stack
*s);
int StackLength(Stack
*s);
int GetTop(Stack
*s, ElemType
*e);
int Push(Stack
**s, ElemType e);
int Pop(Stack
**s, ElemType
*e);
#endifstack.c
#include
<stdio.h>
#include
<stdlib.h>
#include
"stack.h"

/**//*构造一个空栈s*/
int InitStack(Stack
**s)
...{
(*s)->base
= (ElemType
*)malloc(StackInitSize*sizeof(ElemType));
if(!(*s)->base)
exit(0);
(*s)->top
= (*s)->base;
(*s)->stacksize
= StackInitSize;
return
0;
}

/**//*销毁栈s,s不再存在*/
int DestroyStack(Stack
**s)
...{
ElemType
*p;
while((*s)->top
!= (*s)->base)
...{
p
= (*s)->top--;
free(p);
}
p
= NULL;
return
0;
}

/**//*插入元素e为新的栈顶元素*/
int Push(Stack
**s, ElemType e)
...{
if((*s)->top
- (*s)->base
>= (*s)->stacksize)
...{
(*s)->base
= (ElemType
*)realloc((*s)->base,
((*s)->stacksize
+ StackIncrement)*sizeof(ElemType));
if(!(*s)->base)
exit(0);
(*s)->top
= (*s)->base
+ (*s)->stacksize;
(*s)->stacksize
+= StackIncrement;
}
*((*s)->top++)
= e;
return
0;
}

/**//*删除s的栈顶元素,用e返回*/
int Pop(Stack
**s, ElemType
*e)
...{
if((*s)->top
== (*s)->base)
exit(1);
(*s)->top--;
*e =
*((*s)->top);
return
0;
}

/**//*判断栈是否为空*/
int StackEmpty(Stack
*s)
...{
if(s->top
== s->base)
return
1;
else
return
0;
}

/**//*取栈顶元素,用e返回*/
int GetTop(Stack
*s, ElemType
*e)
...{
if(s->top
== s->base)
return
0;
else
...{
*e =
*(s->top
- 1);
return
1;
}
}

/**//*返回栈s元素个数*/
int StackLength(Stack
*s)
...{
return (s->top
- s->base);
}

/**//*把s置为空栈*/
int ClearStack(Stack
**s)
...{
(*s)->top
= (*s)->base;
return
0;
}StackMain.c
#include
<stdio.h>
#include
<stdlib.h>
#include
"stack.h"

/**//*简单实例*/
int main(int argc,
char
**argv)
...{
ElemType elem;
Stack
*s;
s
= (Stack
*)malloc(sizeof(Stack));
InitStack(&s);
while((elem
= getchar())
!= '#')
...{
Push(&s, elem);
}
GetTop(s,
&elem);
printf("The top element is %c
", elem);
printf("The length of the stack is %d
", StackLength(s));
// ClearStack(&s);
Push(&s,
'J');
while(!StackEmpty(s))
...{
Pop(&s,
&elem);
printf("%c
", elem);
}
DestroyStack(&s);
return
0;
}
1024

被折叠的 条评论
为什么被折叠?



