69,369
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
template <class T>
struct node
{
T data;
node* next;
};
template <class T>
class stack
{
public:
stack(): top(NULL) {}
~stack();
int size();
bool IsEmpty() const;
void push(T value);
T Top() const;
void pop();
private:
node<T>* top;
};
template <class T>
stack<T>::~stack()
{
if (top)
{
node<T>* p;
p = top;
top = top->next;
delete p;
}
}
template <class T>
int stack<T>::size()
{
node<T> *p = top;
int num = 0;
while (p)
{
num++;
p = p->next;
}
return num;
}
template <class T>
bool stack<T>::IsEmpty() const
{
if (top)
return false;
return true;
}
template <class T>
void stack<T>::push(T value)
{
node<T>* s = new node<T>;
s->data = value;
s->next = top;
top = s;
}
template <class T>
T stack<T>::Top() const
{
return top->data;
}
template <class T>
void stack<T>::pop()
{
if(top)
{
node<T>* s = top;
top = top->next;
delete s;
}
}
参考一下。
#include<stdio.h>
#include<stdlib.h>
typedef struct Node//定义链栈
{
int a;
struct Node *next;
}LinkedStackNode,*LinkedStack;
LinkedStack LinkedStackInit();
LinkedStack LinkedStackPush(LinkedStack x,int y);
int LinkedStackEmpty(LinkedStack x);
LinkedStack LinkedStackPop(LinkedStack x);
int LinkedStackGetTop(LinkedStack x);
int LinkedStackLength(LinkedStack x);
LinkedStack LinkedStackClear(LinkedStack x);
int main(int argc, char *argv[] )
{
LinkedStack p;
p=LinkedStackInit();
printf("%d\n",LinkedStackEmpty(p));
p=LinkedStackPush(p,3);
printf("%d\n",p->next->a);
p=LinkedStackPop(p);
printf("%d\n",LinkedStackEmpty(p));
p=LinkedStackPush(p,3);
printf("栈顶元素为:%d\n",LinkedStackGetTop(p));
printf("栈长为:%d\n",LinkedStackLength(p));
p=LinkedStackClear(p);
printf("栈已清空\n");
}
LinkedStack LinkedStackInit()//初始化链栈
{
LinkedStack p;
p=(LinkedStack)malloc(sizeof(LinkedStackNode));
p->next=NULL;
return p;
}
int LinkedStackEmpty(LinkedStack x)//判空
{
if(x->next==NULL)
return 1;
else
return 0;
}
LinkedStack LinkedStackPush(LinkedStack x,int y)//入栈
{
LinkedStack p=x,p2;
while(p->next!=NULL)
p=p->next;
p2=(LinkedStack)malloc(sizeof(LinkedStackNode));
p->next=p2;
p2->a=y;
p2->next=NULL;
return x;
}
LinkedStack LinkedStackPop(LinkedStack x)//出栈
{
LinkedStack p=x,p2;
if(x->next==NULL)
{
printf("栈空,无法出栈");
exit(0);
}
else
{
while(p->next->next!=NULL)
p=p->next;
p2=p->next;
free(p2);
p->next=NULL;
return x;
}
}
int LinkedStackGetTop(LinkedStack x)//取栈顶元素
{
LinkedStack p=x;
if(x->next==NULL)
{
printf("栈空");
exit(0);
}
else
{
while(p->next!=NULL)
p=p->next;
return p->a;
}
}
int LinkedStackLength(LinkedStack x)//求栈长
{
int length=0;
LinkedStack p=x;
while(p->next!=NULL)
{
p=p->next;
length++;
}
return length;
}
LinkedStack LinkedStackClear(LinkedStack x)//清空栈
{
x->next=NULL;
return x;
}