数据结构在C程序设计中显得尤为重要,但在C++用好像就好像用到,而且可以用模板编程,好像我们不需要设计数据结构,但要我们自己来设计一栈类又该怎么设计呢?
栈类的头文件
#ifndef STACK_H_
#define STACK_H_
#include<iostream.h>
struct Node
{
int data;
struct Node* next;
};
class Stack
{
public:
Stack();
void push(int x);
void pop(int *e);
void show();
int get_count()
{
return count;
}
private:
Node* top;
Node* bottom;
int count;
};
#endif
栈类的实现
#include"Stack.h"
Stack::Stack()
{
top=NULL;
bottom=top;
count =0;
}
void Stack::push(int x)
{
Node *temp;
temp=new Node;
temp->next=top;
temp->data=x;
top=temp;
count++;
}
void Stack::pop(int *e)
{
Node *temp;
temp=top;
*e = top->data;
top=top->next;
delete temp;
count--;
}
void Stack::show()
{
Node* temp=top;
if(temp==NULL)
{
cout<<"zhan is empty!";
}
else
{
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
}
cout<<endl;
}
main函数
#include <iostream>
#include "Stack.h"
#include <time.h>
int main(void)
{
Stack a;
int x,n,i;
srand(time(0));
int e;
for(i=0;i<10;i++)
{
a.push(rand()%10+1);
}
a.show();
{
a.pop(&e);
}
a.show();
cout << e <<endl;
cout <<a.get_count() <<endl;
return 0;
}