1、使用数组实现一个栈
#include
int a[FILENAME_MAX];
int top = -1;
void Pop();
void Push(int x);
int Top();
void Print();
int main()
{
Push(3);
Push(5);
Push(10);
Print();
Pop();
Print();
}
void Push(int x)
{
if (top == FILENAME_MAX - 1)
{
printf_s("Error:Overflow array!");
return;
}
a[++top] = x;//top++;a[top]=x;
}
void Pop()
{
if (top==-1)
{
printf_s("Error:Empty array!");
return;
}
top--;
}
int Top()
{
return a[top];
}
void Print()
{
if (top == -1)
{
printf_s("Error:Empty Array!");
return;
}
printf_s("Stack is:");
for (int i = 0; i < top; i++)
{
printf_s("%d ", a[i]);
}
printf_s("n");
}
2、使用链表实现一个栈
#include
struct Node
{
int data;
struct Node* next;
};
struct Node* top;
void Push(int x);
void Pop();
void Print();
int main()
{
Push(3);
Push(5);
Push(7);
Print();
Pop();
Print();
}
void Push(int x)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = x;
temp->next = top;
top = temp;
}
void Pop()
{
if (top == NULL) return;
struct Node* temp = top;
top = top->next;
temp->next = NULL;
free(temp);
}
void Print()
{
if (top == NULL) return;
struct Node* temp = top;
printf_s("Stack is:");
while (temp!=NULL)
{
printf_s("%d ", temp->data);
temp = temp->next;
}
printf_s("n");
}