数据结构复习,栈的链表实现,创建空栈时,需要有一个节点作为头结点。
#ifndef DATA_STRUCTURES
#define DATA_STRUCTURES
//Stack链表实现
class StackLinkedList
{
public:
struct Node
{
int element;
Node* next;
};
StackLinkedList() = default; //"告诉"编译器生成默认构造,C++11新特性
StackLinkedList(Node* s);
//创建栈
Node* CreateStack();
//判断栈是否为空
int IsEmpty(Node* s);
void MakeEmpty(Node* s);
//压栈
void Push(int ele, Node* s);
//弹栈
void Pop(Node* s);
};
#endif // DATA_STRUCTURES
#include <iostream>
#include <assert.h>
#include "datastructures.h"
using namespace std;
int StackLinkedList::IsEmpty(Node* s)
{
return (s->next == NULL);
}
void StackLinkedList::Pop(Node* s)
{
if(IsEmpty(s)){
cout << "Empty Stack!" << endl;
return;
}else{
Node* firstCell = s->next;
s->next = firstCell->next;
delete(firstCell);
}
}
void StackLinkedList::MakeEmpty(Node* s)
{
if(s == NULL){
cout << "Error" << endl;
return;
}else{
while (!IsEmpty(s)) {
Pop(s);
}
}
}
StackLinkedList::Node* StackLinkedList::CreateStack() //由于Node是类StackLinkedList中的结构体,做返回值时必须加域作用符
{
Node* p = new Node;
if(NULL == p)
return NULL;
p->next = NULL;
MakeEmpty(p);
return p;
}
void StackLinkedList::Push(int ele, Node* s)
{
assert(s);
Node *ptrTemp = new Node;
if(!ptrTemp)
return;
else{
ptrTemp->element = ele;
ptrTemp->next = s->next;
s->next = ptrTemp;
}
}
int main()
{
cout << "Hello World!" << endl;
return 0;
}