使用无头链表实现栈
新的元素开辟新的空间,放在链表的头部
stack.h
#pragma once
#include<iostream>
#include"Node.h"
class stack {
private:
Node* pHead;
public:
stack() { pHead = NULL; }//注意 最开始的时候stack的phead是NULL
~stack() {
Node* t;
while (pHead) {
t = pHead;
pHead = pHead->link;
t->link = NULL; delete t;
}
}// 往栈中新加入一个结点,新加的结点含有数据i并放在链表的头部。
void put(int i);
// 从栈中取出一个节点,返回该结点的数据值。结点从栈的头部取出,取出后删除该结点。
int get();
};
stack.cpp
#include "stack.h"
#include"Node.h"
#include<iostream>
using namespace std;
void stack::put(int i)
{
if (pHead == NULL)
{
pHead = new Node(i);
Node* t=pHead;
Node* p = new Node(1, t);
pHead = p;
}
else
{
Node* t = pHead;
Node* p = new Node(++pHead->info, t);
pHead->info = i;
pHead = p;
}
}
int stack::get()
{
cout << "num:" << pHead->info-- << endl;
Node* t = pHead->link;
int n = t->info;
pHead->link = t->link;
delete t;
return n;
}
Node.h
#pragma once
#include<iostream>
//#include"student.h"
//typedef student tt;
class Node
{
private:
int info;
Node* link;
public:
Node(int n=0,Node*p=NULL):info(n),link(p){}
friend class stack;
};
main
#include "stack.h"
#include"Node.h"
#include<iostream>
using namespace std;
int main()
{
stack a;
for (int i = 2; i <= 6; i++)
{
a.put(i);
}
for (int i = 1; i <= 5; i++)
cout << a.get() << endl;
}