資料結構之堆疊(c)
阿新 • • 發佈:2019-02-11
相關知識
1.函式封裝
2.堆疊(先進後出,後進先出)
3.指標(記憶體申請,結構體運用)
標頭檔案及其宣告
#ifndef STACKLIST_H_INCLUDED
#define STACKLIST_H_INCLUDED
typedef int ElemType; typedef struct STACK{ ElemType data; struct STACK *next; }Stack; void CreateStack(); Stack *Push(Stack *head,ElemType val);//入棧 ElemType Pop(Stack *head);//出棧 #endif // STACKLIST_H_INCLUDED
主函式
#include <stdio.h> #include <stdlib.h> #include"StackList.h" int main() { int i,x=0,val; Stack *head;//節點頭部初始化 head=(Stack *)malloc(sizeof(Stack)); head->next=NULL; scanf("%d",&x); for(i=0;i<x;i++){ scanf("%d",&val); Push(head,val); } for(i=0;i<x;i++){ printf("%d ",Pop(head)); } return 0; }
StackList.c檔案
#include <stdio.h> #include <stdlib.h> #include"StackList.h" Stack *Push(Stack *head,ElemType val) { Stack *s;//宣告節點指標 s=(Stack *)malloc(sizeof(Stack));//申請記憶體空間 s->data=val; s->next=head->next; head->next=s; return head; } ElemType Pop(Stack *head) { Stack *fre; ElemType TOPre; if(head->next==NULL)return NULL; else { fre=head->next; head->next=fre->next; TOPre=fre->data; free(fre); return TOPre; } }