C++栈(数组/链表实现)

数组实现栈:

#include
#include 
#include 
using namespace std;
int index=-1;
int mSize=100;
int arrStack[100];
void clear(){
	index=-1;
}
int isEmpty(){
	if(index==-1){
		return 1;
	}else{
		return 0;
	}
}
int isFull(){
	if(index==99){
		return 1;
	}else{
		return 0;
	}
}
void top(){
	if(!isEmpty()){
		cout<<arrStack[index];
	}else{
		cout<<"栈为空";
	}
}
void push(int num){
	if(!isFull()){
		arrStack[++index]=num;
	}else{
		cout<<"栈已满";
	}
}
void searchall(){
	if(!isEmpty()){
		int i=index;
		while(i!=-1){
			cout<<arrStack[i--]<<" ";
		}
	}else{
		cout<<"栈为空";
	}
}
void pop(){
	if(!isEmpty()){
		index--;
	}else{
		cout<<"栈为空";
	}
}
int main() {
	push(1);
	push(2);
	push(4);
	push(5);
	pop();
	clear();
	searchall();
	return 0;
}

链表实现栈:

#include
#include 
#include 
using namespace std;
struct Node{
	int data;
	Node *next;
};
Node *head,*p,*r;
void clear(Node *p){
	p->next=NULL;
}
void top(Node *p){
	while(p->next!=NULL){
		p=p->next;
	}
	cout<<p->data;
}
void pop(Node *p){
	Node *temp;
	while(p->next!=NULL){
		temp=p;
		p=p->next;
	}
	temp->next=NULL;
}
void push(Node *head,int data){
	p=new Node();
	p->data=data;
	while(head->next!=NULL){
		head = head->next;
	}
	head->next=p;
}
int main() {
	int x;
	head = new Node();
	push(head,5);
	push(head,3);
	push(head,1);
	pop(head);
	pop(head);
	top(head);
	return 0;
}

你可能感兴趣的:(逻辑练习,c++,链表,数据结构)