//堆栈–>后进先出,先进后出
#include<stdio.h>
#include<stdlib.h>
struct stackNode{
int data;
struct stackNode *nextPtr;
};
typedef struct stackNode Stacknode;
typedef Stacknode* StacknodePtr;
void push(StacknodePtr *topPtr, int number);
int pop(StacknodePtr *topPtr);
void printList(StacknodePtr topPtr);
int isEmpty(StacknodePtr topPtr);
int main()
{
StacknodePtr startPtr = NULL;
int choice;
int value;
printf("Enter your choice from the following.\n"
" 1 to fill the number at the list top.\n"
" 2 to remove the number from the list top.\n"
" 3 to end.\n? ");
scanf("%d", &choice);
while(choice != 3){
switch(choice){
case 1:
printf("Enter an integer: \n");
scanf("%d", &value);
push(&startPtr, value);
printf("%d has been added into the list.\n"
" The list after adding a value is\n", value);
printList(startPtr);
break;
case 2:
if(!isEmpty(startPtr)){
printf("%d has been deleted from the list.\n", pop(&startPtr));
printf("The list after deleted is :\n");
printList(startPtr);
}
else{
printf("The list is empty.\n");
printf("Please choose a command again.\n");
}
break;
default:
printf("You enter a wrong command,\n");
printf("Please choose a command again.\n");
break;
}
printf("? ");
scanf("%d", &choice);
}
printf("End of run.\n");
return 0;
}
void push(StacknodePtr *topPtr, int number)
{
StacknodePtr newPtr; //用于存放要放入的结构(节点)
newPtr = (StacknodePtr)malloc(sizeof(Stacknode));
if(newPtr == NULL){
printf("No memmery is available.\n");
}
else{
newPtr->data = number;
newPtr->nextPtr = *topPtr;
*topPtr = newPtr;
}
}
int pop(StacknodePtr *topPtr)
{
int backnumber;
StacknodePtr tempPtr;
tempPtr = *topPtr;
backnumber = tempPtr->data;
*topPtr = (*topPtr)->nextPtr;
free(tempPtr);
return backnumber;
}
void printList(StacknodePtr topPtr)
{
if(topPtr == NULL){
printf(“NULL\n”);
}
else{
while(topPtr != NULL){
printf("%d–>", topPtr->data);
topPtr = topPtr->nextPtr;
}
printf(“NULL\n”);
}
}
int isEmpty(StacknodePtr topPtr)
{
if(topPtr == NULL){
return 1;
}
else{
return 0;
}
}
来源:CSDN
作者:静水无心
链接:https://blog.csdn.net/weixin_44160256/article/details/104558634