堆栈--后进先出

北慕城南 提交于 2020-03-02 10:31:17

//堆栈–>后进先出,先进后出

#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;
}
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!