利用鏈表的結構實現棧的功能---入棧、出棧、清空
代碼如下:
linkstack.h 鏈表棧的頭文件
#include <iostream>
class Node
{
public:
int data;
Node * next;
};
class stack
{
private:
Node *head;
Node *pcurr;
int length;
public:
stack()
{
head = NULL;
int len = 0; // 有頭結點後lens初始值爲0
}
void push(int val);//入棧
int pop();//出棧
int len();//判斷長度
bool isEmpty();//
void clear();//清空棧中所有元素
};
linkstack.cpp 鏈表棧的子函數功能實現
#include "linkstack.h"
using namespace std;
void stack::push(int val)
{
Node *ptemp ;
ptemp = new Node();
ptemp->data = val;
length++;
if(head == NULL)
{
ptemp->next = head;
head = ptemp;
pcurr = ptemp;
}
else
{
ptemp->next = pcurr;
pcurr = ptemp;
}
}
bool stack::isEmpty()
{
if(length == 0)
return 1;
else
return false;
}
int stack::pop()
{
if(isEmpty() == 1)
{
cout << "is empty" << endl;
return 0;
}
else
{
Node *ptemp ;
ptemp = new Node();
length--;
ptemp = pcurr;
int data = pcurr->data; //返回刪除元素的值;
delete(ptemp);// 刪除該元素
pcurr = pcurr->next;
cout <<"需要刪除的元素"<< data << endl;
return data;
}
}
void stack::clear()
{
if(length > 0)
pop();
}
測試主函數:
#include "linkstack.h"
using namespace std;
int main()
{
stack stack;
if (stack.isEmpty() == 0)
cout << "is empty" << endl;
stack.push(1);
stack.push(2);
stack.push(3);
stack.pop();
stack.clear();
stack.isEmpty();
if (stack.isEmpty() == 0)
cout << "is empty" << endl;
system("pause");
return 0;
}