C語言一個棧的實現
阿新 • • 發佈:2019-01-08
棧是常用的資料結構之一,下面給出一個鏈式棧的實現~~
標頭檔案Stack.h
- #ifndef Stack_H
- #define Stack_H
- typedefint Item;
- typedefstruct node * PNode;
- /*定義棧節點型別*/
- typedefstruct node
- {
- Item data;
- PNode down;
- }Node;
- /*定義棧型別*/
- typedefstruct stack
- {
- PNode top;
- int size;
- }Stack;
- /*構造一個空棧*/
-
Stack *InitStack();
- /*銷燬一個棧*/
- void DestroyStack(Stack *ps);
- /*把棧置空*/
- void ClearStack(Stack *ps);
- /*判定是否為空棧*/
- int IsEmpty(Stack *ps);
- /*返回棧大小*/
- int GetSize(Stack *ps);
- /*返回棧頂元素*/
- PNode GetTop(Stack *ps,Item *pitem);
- /*元素入棧*/
- PNode Push(Stack *ps,Item item);
- /*元素出棧*/
- PNode Pop(Stack *ps,Item *pitem);
- /*遍歷棧並訪問visit函式*/
-
void
- #endif
實現部分Stack.c
- #include"Stack.h"
- #include<malloc.h>
- #include<stdlib.h>
- /*構造一個空棧*/
- Stack *InitStack()
- {
- Stack *ps = (Stack *)malloc(sizeof(Stack));
- if(ps!=NULL)
- {
- ps->top = NULL;
-
ps->size = 0;
- }
- return ps;
- }
- /*判定是否為空棧*/
- int IsEmpty(Stack *ps)
- {
- if(ps->top == NULL && ps->size == 0)
- return 1;
- else
- return 0;
- }
- /*返回棧大小*/
- int GetSize(Stack *ps)
- {
- return ps->size;
- }
- /*元素入棧*/
- PNode Push(Stack *ps,Item item)
- {
- PNode pnode = (PNode)malloc(sizeof(Node));
- if(pnode != NULL)
- {
- pnode->data = item;
- pnode->down = GetTop(ps,NULL);
- ps->size++;
- ps->top = pnode;
- }
- return pnode;
- }
- /*返回棧頂元素*/
- PNode GetTop(Stack *ps,Item *pitem)
- {
- if(IsEmpty(ps)!=1&&pitem!=NULL)
- {
- *pitem = ps->top->data;
- }
- return ps->top;
- }
- /*元素出棧*/
- PNode Pop(Stack *ps,Item *pitem)
- {
- PNode p = ps->top;
- if(IsEmpty(ps)!=1&&p!=NULL)
- {
- if(pitem!=NULL)
- *pitem = p->data;
- ps->size--;
- ps->top = ps->top->down;
- free(p);
- }
- return ps->top;
- }
- /*銷燬一個棧*/
- void DestroyStack(Stack *ps)
- {
- if(IsEmpty(ps)!=1)
- ClearStack(ps);
- free(ps);
- }
- /*把棧置空*/
- void ClearStack(Stack *ps)
- {
- while(IsEmpty(ps)!=1)
- {
- Pop(ps,NULL);
- }
- }
- /*遍歷棧並訪問visit函式 */
- void StackTraverse(Stack *ps,void (*visit)(Item item))
- {
- PNode p = ps->top;
- int i = ps->size;
- while(i--)
- {
- visit(p->data);
- p = p->down;
- }
- }
測試部分Test.c
- #include"Stack.h"
- #include<stdio.h>
- void print(Item i)
- {
- printf("該節點元素為%d\n",i);
- }
- main()
- {
- Stack *ps = InitStack();
- int i,item;
- printf("0-9依次入棧並輸出如下:\n");
- for(i=0;i<10;i++)
- {
- Push(ps,i);
- GetTop(ps,&item);
- printf("%d ",item);
- }
- printf("\n從棧頂到棧頂遍歷並對每個元素執行print函式:\n");
- StackTraverse(ps,print);
- printf("棧中元素依次出棧並輸出如下:\n");
- for(i=0;i<10;i++)
- {
- Pop(ps,&item);
- printf("%d ",item);
- }
- ClearStack(ps);
- if(IsEmpty(ps))
- printf("\n將棧置空成功\n");
- DestroyStack(ps);
- printf("棧已被銷燬\n");
- }