1. 程式人生 > >鏈棧的基本接口實現

鏈棧的基本接口實現

null ack sta std 刪除 can emp ext nbsp

#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TRUE   1
#define FALSE  0
#define OK     1
#define ERROR  0
#define IBFEASIBLE  -1
#define OVERFLOW    -2 

typedef int Status;
typedef int ElemType; /* 元素類型為int類型*/

//鏈棧類型 
typedef struct LSNode{ 
    ElemType data;        
//數據域 struct LSNode *next; //指針域 }LSNode, *LStack; //結點和鏈棧類型 Status InitStack_LS(LStack &S); void DestroyStack_LS(LStack &S); Status StackEmpty_LS(LStack S); Status Push_LS(LStack &S,ElemType e); Status Pop_LS(LStack &S,ElemType &e); Status GetTop_LS(LStack S, ElemType
&e); Status Traverse(LStack S); int LengthLStack(LStack S); //鏈棧的基本操作實現代碼如下: //1.初始化鏈棧 Status InitStack_LS(LStack &S){ S=(LSNode*)malloc(sizeof(LSNode)); if(S==NULL)return OVERFLOW; S->next = NULL; return OK; } //2.銷毀鏈棧 void DestroyStack_LS(LStack &S){ LStack p=S->next,q=S;
while(p){ free(q); q=p; p=p->next; } free(p); } //3.判空操作 Status StackEmpty_LS(LStack S){ if(S->next==NULL){ return TRUE; }else{ return FALSE; } } //4.入棧 Status Push_LS(LStack &S,ElemType e){ LSNode *t; t=(LSNode*)malloc(sizeof(LSNode));//為元素e分配空間 if(t==NULL) return FALSE; t->data=e; t->next=S; S=t; return OK; } //5.出棧 Status Pop_LS(LStack &S,ElemType &e){ LSNode *t; if(S==NULL) return ERROR; t=S; //t指向棧頂元素的節點 e=S->data; S=S->next; //刪除棧頂結點 free(t); //釋放節點t return OK; } //6.取出棧頂元素 Status GetTop_LS(LStack S,ElemType &e){ if(S==NULL) return ERROR; e=S->data; return OK; } //7.鏈棧的長度 int LengthLStack(LStack S){ int length; while(S->next){ S=S->next; length++; } return length; } //8.遍歷棧 Status Traverse(LStack S) { LSNode *p; p = S; while (p->next){ printf("%4d", p->data); p=p->next; } printf("\n"); return OK; } int main(){ int i,e,j,m; LStack S; do{ printf("1.初始化鏈棧\n"); printf("2.銷毀鏈棧\n"); printf("3.判斷鏈棧是否為空\n"); printf("4.將元素壓入棧\n"); printf("5.棧頂元素出棧\n"); printf("6.取棧頂元素,並返回\n"); printf("7.鏈棧的長度\n"); printf("8.遍歷鏈棧元素\n"); printf("請輸入你要進行的操作:\n"); scanf("%d",&i); switch(i){ case 1 : if(InitStack_LS(S)){ printf("初始化成功\n"); printf("請輸入5個元素進棧:\n"); for(j=0;j<5;j++){ scanf("%d",&e); Push_LS(S,e); } }else{ printf("初始化失敗\n"); } break; case 2 : DestroyStack_LS(S); printf("銷毀棧成功\n"); break; case 3 : if(StackEmpty_LS(S)){ printf("鏈棧為空!\n"); }else{ printf("鏈棧不為空!\n"); } break; case 4 : printf("請輸入壓入棧元素的值:\n"); scanf("%d",&e); if(Push_LS(S,e)){ printf("成功壓入\n"); }else{ printf("壓入失敗\n"); } break; case 5 : Pop_LS(S, m); printf("成功出棧,數值為:%d\n",m); break; case 6 : GetTop_LS(S,m); printf("取出棧頂元素的值:%d\n",m); break; case 7 : printf("鏈棧的長度為:%d\n",LengthLStack(S)); break; case 8 : printf("鏈表中元素:"); Traverse(S); break; } }while(i>0&&i<=8); return 0; }

鏈棧的基本接口實現