做网站每年包多少流量百度手机版网页
近日研读《大话数据结构》,通过C++实现基本数据结构的代码。
栈的定义于上一篇文章阐明,于此不再赘述,下面直接放上通过链表实现的栈的链式存储结构的代码,由于鄙人才疏学浅,尚不能将自己的代码应用于实际生活中,故此尽仅在主函数中加入了简单的测试数据,大体上仍停留在面向过程编程的阶段,但栈的实现及其主要功能基本完备,放上代码与大家共享。
#include <iostream>
using namespace std;
typedef int ElemType;
struct node{node *next;ElemType data;
};
struct topnode{node *top;int length;
}*head;
bool setStack(int n){if(n<=0) return false;head=new topnode;head->length=0;node *p,*q;p=new node;cout<<"请输入压入栈中的数据";cin>>p->data;head->top=p;head->length++;p->next=NULL;for(int i=1;i<n;i++){q=p;p=new node;p->next=q;cout<<"请输入压入栈中的数据";cin>>p->data;head->length++;}head->top=p;return true;
}
int main()
{int n;cout<<"请输入所建立栈的长度:";cin>>n;if(setStack(n)){//输出栈中数据信息node *p=head->top;while(p!=NULL){int cnt=1;cout<<"栈中第"<<cnt++<<"个数据的值为:"<<p->data<<endl;p=p->next;} }else{cout<<"非法输入~"<<endl;}cout<<"Done!Bye~"<<endl;return 0;
}
明日将奉上数据结构栈与算法结合的应用,以及实现数据结构队列的代码,敬请期待~