小言_互联网的博客

数据结构课——栈的基本操作c++实现

343人阅读  评论(0)

 栈的基本操作——c++实现

#include<bits/stdc++.h>
using namespace std;

struct Node
{
	int data;
	Node *next;
	Node();
	Node(int d,Node *n);
};
Node::Node()
{
	data = 0;
	next = NULL;
}
Node::Node(int d, Node *n)
{
	data = d;
	next = n;
}
class LinkStack
{
public:
	Node *top;
	//建栈
	LinkStack()
	{
        top = new Node();
    }
    //插入操作
	void Push(int d)
	{
        Node *newNode = new Node(d,top->next);
        top->next = newNode;
        cout << "StackLinkList Push " << newNode->data << endl;
    }
    //删除操作
    void Pop()
    {
        cout << "StackLinkList Pop " << top->next->data << endl;
        Node *p = top->next;
        Node *t = p->next;
        top->next = t;
        delete p;
    }
    //取栈顶元素
    void Top()
    {
        cout << "StackLinkList Top " << top->next->data << endl;
    }
    //清空操作
    void Clear()
    {
        Node *p = top;
        while (p->next != NULL)
        {
            cout << "StackLinkList Clear " << p->next->data << "   ";
            Pop();
        }
    }
    //栈的元素的个数
    void Length()
    {
        Node *p = top;
        int count = 0;
        while (p->next != NULL)
        {
            count++;
            p = p->next;
        }
        cout << "StackLinkList Length " << count << endl;
    }
    //便利
    void Show()
    {
        Node *p = top;
        while (p->next != NULL)
        {
            p = p->next;
            cout << "StackLinkList Node " << p->data << endl;
        }
    }
    //判断栈是否为空
    void Empty()
    {
        if (top->next != NULL)
        {
            cout << "StackLinkList Not Empty"<< endl;
        }
        else
        {
            cout << "StackLinkList Empty" << endl;
        }
    }

};
int main()
{
	LinkStack LS;
	LS.Push(1);
	LS.Push(2);
	LS.Push(3);
	LS.Push(4);
	LS.Push(5);
	LS.Top();
	LS.Show();
	LS.Length();
	LS.Empty();
	LS.Pop();
	LS.Top();
	LS.Show();
	LS.Length();
	LS.Clear();
	LS.Length();
	LS.Empty();
}

 


转载:https://blog.csdn.net/qq_43641702/article/details/101751196
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场