《天勤数据结构》笔记——顺序栈和链栈及其代码实现(C/C++)
生活随笔
收集整理的這篇文章主要介紹了
《天勤数据结构》笔记——顺序栈和链栈及其代码实现(C/C++)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、順序棧
#include <stdio.h>#define maxSize 100typedef struct{int data[maxSize];int top; }SqStack;//&是運用了C++的引用參數 //初始化棧,將棧頂指針置為-1 void initStack(SqStack &st){st.top=-1; }//棧為空時返回1,否則返回0 int isEmpty(SqStack st){if (st.top==-1)return 1;elsereturn 0; }//進棧,入棧成功返回1,否則返回0 int push(SqStack &st, int x){if (st.top==maxSize-1)return 0;++(st.top);st.data[st.top]=x;return 1; }//出棧,出棧成功返回1,否則返回0 int pop(SqStack &st, int &x){if (st.top==-1)return 0;x=st.data[st.top];--(st.top);return 1; }//打印當前棧中元素 void printStack(SqStack st){for (int i=0; i<=st.top; i++){printf ("%d ", st.data[i]);} }int main(){SqStack s;initStack(s);push(s, 5);push(s, 3);push(s, 20);int x;pop(s, x);printf("x=%d\n", x);printStack(s);return 0; }二、鏈棧
#include <stdio.h> #include <stdlib.h> typedef struct lineStack{int data;struct lineStack *next; }lineStack;//鏈棧初始化,使用引用型參數 void initStack(lineStack *&lst){lst=(lineStack*)malloc(sizeof(lineStack));lst->next=NULL; }//棧為空返回1,否則返回0 int isEmpty(lineStack *lst){if (lst->next==NULL)return 1;elsereturn 0; }//入棧 void push(lineStack *lst, int x){lineStack *temp;temp=(lineStack*)malloc(sizeof(lineStack));temp->next=NULL;temp->data=x;temp->next=lst->next;lst->next=temp; }//出棧,返回1出棧成功,否則失敗 int pop(lineStack *lst, int &x){lineStack *temp;if (lst->next==NULL)return 0;temp=lst->next;x=temp->data;lst->next=temp->next;free(temp);return 1; }//打印鏈棧 void printLineStack(lineStack *lst){lineStack *p=lst->next;while (p!=NULL){printf("%d ", p->data);p=p->next;} }int main(){lineStack *ls;initStack(ls);push(ls, 5);push(ls, 232);push(ls, 24);int x;pop(ls, x);printf("x=%d\n", x);printLineStack(ls);return 0; }?
總結
以上是生活随笔為你收集整理的《天勤数据结构》笔记——顺序栈和链栈及其代码实现(C/C++)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [VGG16]——网络结构介绍及搭建(P
- 下一篇: 《天勤数据结构》笔记——使用两个栈实现共