链栈
- linkStack.h文件
#pragma once
typedef struct Node {
int data;
struct Node* next;
}node, * pnode;
class LinkStack {
private:
Node* top;
public:
LinkStack();
~LinkStack();
void push(int x);
int pop();
int getTop();
bool isEmpty();
void display();
};
- LinkStack.cpp文件
#include<iostream>
#include"LinkList.h"
LinkStack::LinkStack() {
top = NULL;
}
LinkStack::~LinkStack() {
while (top) {
struct Node* q = top;
top = top->next;
delete q;
}
}
void LinkStack:: push(int x){
pnode p = new node;
p->data = x;
p->next = top->next;
top->next = p;
}
int LinkStack::pop() {
int temp = top->data;
pnode q = top;
top = top->next;
delete q;
return temp;
}
int LinkStack::getTop() {
int temp = top->data;
return temp;
}
bool LinkStack::isEmpty() {
if (top == NULL) {
return 1;
}
else {
return 0;
}
}
void LinkStack::display() {
pnode p = top;
while (p) {
cout << p->data;
p = p->next;
}
}
- 测试文件
#include<iostream>
#include"LinkStack.h"
using namespace std;
int main() {
LinkStack st1;
int n = 0;
cout << "输入入栈数据个数" << endl;
cin >> n;
int* number = new int[n];
for (int i = 0; i < n; i++)
cin >> number[i];
int i = 0;
while (i < n) {
st1.push(number[i]);
i++;
}
st1.display();
int count = st1.pop();
st1.display();
}
问题总结
- 头文件格式
//Circle_queue 头文件名
#ifndef CIRCLE_QUEUE_H //就是头文件名(全大写后加个_H)
#define CIRCLE_QUEUE_H
//代码...
#endif
- 类的私有成员top是指针,用来指向链表的第一个元素(无头结点),但是再未指向之前,是个空指针,如果用以下方式进行入栈操作会发生错误
void LinkStack::push(int x) {
pnode p = new node;
p->data = x;
p->next = top->next;
top = p;
}
标签:LinkStack,int,top,next,链栈,pnode,data
From: https://www.cnblogs.com/Dllsss/p/18213956