最近在复习数据结构,顺便看看大一的时候写的代码,看完之后比当初有了更加深刻的体会。
希望这些能提供给初学者一些参考。
1.共享栈的实现
//共享栈
#define MaxSize N
typedef struct
{
ElementType elem[MaxSize];
int top1, top2;
}ShareStack;
//入栈 Push(s, e)
void Push (ShareStack *s, ElementType e, int i)
{
if (s->top1+1 == s->top2)
printf("Full");
else if (1 == i)
{
s->top1++;
s->elem[s->top1] = e;
}
else if (2 == i)
{
s->top2--;
s->elem[s->top2] = e;
}
}
//出栈 Pop(s)
ElementType Pop (ShareStack *s, int i)
{
if (1 == i)
{
if (-1 == s->top1)
return (nil);
else
{
e = s->elem[s->top1];
s->top1--;
}
}
if (2 == i)
{
if (MaxSize-1 == s->top2)
return (nil);
else
{
e = s->elem[s->top2];
s->top2++;
}
}
return (e);
}
2.求自然数的阶乘
int Fact (int x)
{
result = 1;
s = (StackNode *)malloc(sizeof(StackNode)); //建立栈的头结点
s->next = NULL;
while (x)
{
p = (StackNode *)malloc(sizeof(StackNode));
p->data = x;
p->next = s->next;
s->next = p;
x--;
}
while (!(s->next))
{
p = s->next;
s->next = p->next;
result *= p->data;
free(p);
}
return result;
}
3.将十进制转换为十进制以下其它进制的数
int Conversion (int n, int d)
{
SeqStack s;
int result = 0;
s.top = -1;
while (n)
{
push(s, n%d);
n / d;
}
while (!StackEmpty(s))
result = result * 10 + pop(s);
return result;
}