stack类 栈类

使用无头链表实现栈
新的元素开辟新的空间,放在链表的头部
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;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值