栈的链表存储实现---(附完整程序)

#include<stdio.h>
#include<stdlib.h>
 
typedef struct SNode * PtrToSNode;
struct SNode{
	int Data;
	PtrToSNode Next;
}; 
typedef PtrToSNode Stack;

//创建堆栈
Stack CreateStack(){
	Stack S;
	S = (Stack)malloc(sizeof(struct SNode));
	S->Next=NULL;
	return S;
} 

//入栈
bool IsEmpty(Stack S){
	return (S->Next==NULL);
} 
bool Push(Stack S,int X){
	PtrToSNode TmpCell;
	TmpCell = (PtrToSNode)malloc(sizeof(struct SNode));
	TmpCell->Data=X;
	TmpCell->Next=S->Next;
	S->Next=TmpCell;
	printf("入栈成功\n"); 
}

//出栈
int Pop(Stack S) {
	PtrToSNode FirstCell;
	int TopElem;
	if(IsEmpty(S)){
		printf("堆栈空\n");
	}
	else{
		FirstCell=S->Next;
		TopElem=FirstCell->Data;
		S->Next=FirstCell->Next;
		free(FirstCell);
		return TopElem;
	}
}

int main(){
	//初始化 
	Stack S = CreateStack();
	int i,n,z,q;
	//入栈 
	printf("需要入栈几个数:");
	scanf("%d",&n);
	for(i=0;i<n;i++){
		scanf("%d",&z);
		Push(S,z);
	}
	
	//出栈
	printf("出栈的顺序为:\n");
	while(!IsEmpty(S)){
		q = Pop(S);
		printf("%d ",q);
	}
	return 0;
}

运行结果:

阅读更多

没有更多推荐了,返回首页