資料結構-堆疊-連結串列實現
阿新 • • 發佈:2018-11-27
/*
* 堆疊 連結串列實現
*
* */
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
//定義結構
typedef struct _Stack * Stack;
struct _Stack{
int data;
Stack next;
};
//建立一個堆疊
Stack CreakStack(){
Stack stack=(Stack)malloc(sizeof(struct _Stack));
stack->next=NULL;
return stack;
}
//判斷是否為空
bool isEmpty(Stack stack){
return (stack->next==NULL);
}
//壓棧
bool Push(Stack stack,int num){
Stack stack1=(Stack)malloc(sizeof(struct _Stack));
stack1->data=num;
stack1->next=stack->next;
stack->next=stack1;
return true;
}
//出棧
int Pop(Stack stack ){
if(isEmpty(stack)){
printf("堆疊空");
return NULL;
}
else{
Stack stack1;
int numS;
stack1=stack->next;
numS=stack1->data;
stack->next=stack1->next;
free(stack1);
return numS;
}
}
//測試
int main(){
Stack stack=CreakStack();
Pop(stack);
for (int i = 0; i < 10; i++) {
Push(stack,i);
}
Push(stack,10);
for(int i=0;i<10;i++){
printf("%d ",Pop(stack));
}
return 0;
}