求2道题算法

来源:百度知道 编辑:UC知道 时间:2024/06/17 18:12:29
1 试编写一个算法,计算一个循环队列中包含的元素个数。
2 试编写一个算法,实现链栈的入栈出栈操作。

链栈的C实现

//开始
#include <stdio.h>
#include <malloc.h>

typedef struct node node;
typedef struct stack stack;
typedef int valueType; //此处 int 应替换为实际使用时的类型

struct node {
valueType value;
node *preNode;
};

struct stack {
node *topNode;
int nodeNum;
};

stack * initStack(void) { //构造新栈 通过返回指针访问
stack * newStack = malloc(sizeof(stack));
newStack->nodeNum = 0;
return newStack;
}

void Push(stack * targetStack, valueType nodeValue) { //Push 接受两个参数 目标栈 和 具体值
node * newNode = malloc(sizeof(node));
newNode->value = nodeValue;
if (targetStack->nodeNum) {
newNode->preNode = targetStack->topNode;
}
targetStack->topNode = newNode;
targetStack->nodeNum++;
}

valueType Pop(stack * targetStack) { //Pop 接受一个参数 目标栈 返回栈顶的值
if (!targetStack->nodeNum) {
printf(&quo