level 7
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct Stack* createStack(void);//1
bool isEmpty(struct Stack* s);//3
void disposeStack(struct Stack* s);//7
void makeEmpty(struct Stack* s);//2
void push(int x, struct Stack* s);//4
int top(struct Stack* s);//5
void pop(struct Stack* s);//6
struct Stack
{
int element;
struct Stack* next;
};
int main(void)
{
int val;
struct Stack* s;
s = createStack();
push(5, s);
push(2, s);
disposeStack(s);
printf("==================\n");
val = top(s);
printf("top val is: %d\n", val);
printf("==================\n");
pop(s);
val = top(s);
printf("top val is: %d\n", val);
printf("==================\n");
push(6, s);
push(7, s);
disposeStack(s);
printf("==================\n");
makeEmpty(s);
printf("stack isEmpty:%d\n", isEmpty(s));
return 0;
}
struct Stack* createStack(void)
{
struct Stack* s;
s = (struct Stack*)malloc(sizeof(struct Stack));
if (s == NULL)
{
printf("Out of space!\n");
return NULL;
}
s->next == NULL;
return s;
}
void makeEmpty(struct Stack* s)
{
if (s == NULL)
{
printf("Must use createStack first.\n");
return;
}
else
{
while(!isEmpty(s))
{
pop(s);
}
}
return;
}
bool isEmpty(struct Stack* s)
{
return s->next == NULL;
}
void push(int x, struct Stack* s)
{
struct Stack* tmp;
tmp = (struct Stack*)malloc(sizeof(struct Stack));
if (tmp == NULL)
{
printf("Out of space!\n");
return;
}
else
{
tmp->element = x;
tmp->next = s->next;
s->next = tmp;
}
return;
}
int top(struct Stack* s)
{
if (!isEmpty(s))
{
return s->next->element;
}
printf("empty stack\n");
return 0;
}
void pop(struct Stack* s)
{
struct Stack* tmp;
if (isEmpty(s))
{
printf("empty stack\n");
return;
}
else
{
tmp = s->next;
s->next = s->next->next;
free(tmp);
}
return;
}
void disposeStack(struct Stack* s)
{
struct Stack* tmp;
tmp = s->next;
while (tmp != NULL)
{
printf("element is %d\n", tmp->element);
tmp = tmp->next;
}
return;
}
2024年02月05日 06点02分
