Stack的c实现

用c语言实现stack的初始化,push,pop和Clear操作

#include<stdio.h>
#include<stdlib.h>
#include<assert.h> struct Link
{
int data;
struct Link* Next;
}; struct Stack
{
struct Link* head;
int Size;
}; void StackInit(struct Stack* sta)
{
sta->head = NULL;
sta->Size = ;
} void StackPush(struct Stack* sta, const int data)
{
struct Link* node;
node = (struct Link*)malloc(sizeof(struct Link));
assert(node != NULL);
node->data = data;
node->Next = sta->head;
sta->head = node;
++ sta->Size;
} int StackEmpty(struct Stack* sta)
{
if(sta->Size == )
return ;
return ;
} int StackPop(struct Stack* sta, int* data)
{
if(StackEmpty(sta))
return ;
struct Link* tmp = sta->head;
*data = sta->head->data;
sta->head = tmp->Next;
free(tmp);
-- sta->Size;
return ;
}
void StackClear(struct Stack* sta)
{
struct Link* tmp;
while(sta->head)
{
tmp = sta->head;
sta->head = tmp->Next;
free(tmp);
}
sta->Size = ;
} int main()
{
struct Stack sta;
StackInit(&sta);
int i;
for(i=; i<=; i++)
StackPush(&sta, i);
while(!StackEmpty(&sta))
{
StackPop(&sta, &i);
printf("%d\n", i);
}
return ;
}

  C++实现

#include <iostream>
using namespace std; class Stack
{
struct Link
{
int data;
Link* Next;
Link(int data_, Link* Next_):data(data_), Next(Next_)
{ }
};
public:
Stack():head(),Size()///初始化,构造函数;
{ }
~Stack()
{
Link* tmp;
while(head)
{
tmp = head;
head = head->Next;
delete tmp;
}
}
void Push(const int data)///插入data;
{
Link* node = new Link(data, head);
head = node;
++ Size;
}
bool Empty()
{
return (Size==);
}
bool Pop(int& data)
{
if(Empty())
return false;
Link* tmp = head;
data = head->data;
head = head->Next;
delete tmp;
Size--;
return true;
}
private:
Link* head;
int Size;
}; int main()
{
Stack sta;
int i;
for(i=; i<=; i++)
{
sta.Push(i);
}
while(!sta.Empty())
{
sta.Pop(i);
cout << i << endl;
}
return ;
}
上一篇:调用Interop.zkemkeeper.dll无法使用解决方案


下一篇:详解Eclipse断点