栈Stack的链表实现
程序员文章站
2024-01-28 16:53:34
...
本节Jungle用链表指针实现栈和栈的基本操作(入栈、出栈、是否为空栈、打印栈元素、销毁栈)。
头文件List_Stack.h里定义栈结构和栈的基本操作:
#ifndef LIST_STACK
#define LIST_STACK
typedef struct STACK
{
int data;
struct STACK* next;
}Stack;
//栈顶指针
Stack* topNode;
bool isEmpty()
{
return topNode == NULL;
}
void push(int iData)
{
Stack *currentNode;
currentNode = (Stack*)malloc(sizeof(Stack));
if(currentNode == NULL)
printf("分配内存失败!\n");
currentNode->data = iData;
currentNode->next = topNode;
topNode = currentNode;
}
void pop()
{
if(isEmpty())
{
printf("The Stack is Empty!\n");
return;
}
Stack *currentNode;
currentNode = topNode;
topNode = topNode->next;
free(currentNode);
}
///销毁栈
void deleteStack()
{
Stack *tempNode;
if(isEmpty())
{
printf("The Stack is Empty!\n");
return;
}
tempNode = topNode;
while(topNode->next!=NULL)
{
tempNode = topNode->next;
free(topNode);
topNode = tempNode;
}
free(topNode);
topNode = NULL;
}
void printStack()
{
if(isEmpty())
{
printf("The Stack is Empty!\n");
return;
}
Stack *currentNode = topNode;
while(currentNode != NULL)
{
printf("%d\t",currentNode->data);
currentNode = currentNode->next;
}
printf("\n");
}
#endif //LIST_STACK
主程序里测试
#include <stdlib.h>
#include <stdio.h>
#include "List_Stack.h"
int main()
{
int num=0;
int choice=0;
while(choice!=6)
{
printf("请选择:\n\t1-是否为空栈\n\t2-入栈(push)\n\t3-出栈(Pop)\n\t4-打印\n\t5-销毁链表\n\t6-退出\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
if(isEmpty())
printf("栈为空栈!\n");
else
printf("不是空栈!\n");
break;
case 2:
int num;
printf("请输入入栈元素值:");
scanf("%d",&num);
push(num);
break;
case 3:
pop();
break;
case 4:
printStack();
break;
case 5:
deleteStack();
break;
}
}
system("pause");
return 0;
}
下一篇: jquery焦点图支持手机触屏