1. 程式人生 > >資料結構作業的程式碼——————棧的鏈式實現

資料結構作業的程式碼——————棧的鏈式實現

作業code2:

  • 仿照作業code1的功能,將課本上鍊表的實現棧的功能完整實現
  • 需要通過main函式呼叫並能進行友好的人機互動輸入
#include<bits/stdc++.h>
#define ElemType  int
#define SElemType int
#define Status    int
#define ERROR     0
#define OK        1

using namespace std;

typedef struct StackNode{//構造棧的節點
        ElemType data;
        struct StackNode *
next; }StackNode,*LinkStack; LinkStack S,p; Status InitStack(LinkStack &S)//初始化棧 { S=NULL; return OK; } Status Push(LinkStack &S,SElemType &e)//在棧頂插入元素e { p = new StackNode; //生成新節點 p->data = e; //將新節點資料域置為e p->next = S; //將新節點插入棧頂
S = p; //修改棧頂指標為p; return OK; } Status Pop(LinkStack &S,SElemType &e)//刪除棧頂元素,用e返回其值 { if(S == NULL) return ERROR; //棧空 e = S->data; //將棧頂元素賦給e p = S; //用p臨時儲存棧頂元素空間,以備釋放 S = S->next;
//修改棧頂指標 delete p; //釋放棧頂元素的空間 return OK; // } Status GetTop(LinkStack S) { if(S != NULL) return S->data; } void display(struct StackNode* head)//遍歷棧 { struct StackNode *current; current = head; if(current!= NULL) { printf("Stack: "); do { printf("%d ",current->data); current = current->next; } while (current!= NULL); printf("\n"); } else { printf("The Stack is empty!\n"); } } int empty(struct node* head) { return head == NULL ? 1 : 0; } void menu() { cout<<" menu:"<<endl; cout<<"1.進棧"<<endl; cout<<"2.出棧"<<endl; cout<<"3.輸出"<<endl; cout<<"4.menu"<<endl; cout<<"0.結束"<<endl; } void preface() { printf(" *********************************************\n" " * *\n" " * 此程式的功能: *\n" " * 將整數型別的資料進行棧的操作 *\n" " * *\n" " *********************************************\n" "\n\n" ); } int main() { SElemType e,x; InitStack(S); preface(); menu(); int choose; while(true) { cout<<"\n請選擇:"; cin>>choose; int k=0; switch(choose) { case 1: cout<<"請輸入需要進棧的個數:"; cin>>x; cout<<"請輸入"<<x<<"個元素:"; while(x--) { cin>>e; Push(S,e); } break; case 2: if(Pop(S,e)) cout<<"出棧的元素是"<<e<<endl; else printf("The Stack is empty!\n"); break; case 3: display(S); break; case 4: menu(); break; case 0: k=1; break; default: cout<<"請重新輸入!"; break; } if(k) break; } return 0; }

參考: