ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

C++数据结构——栈

2020-09-17 21:02:55  阅读:143  来源: 互联网

标签:Node node head temp int C++ next 数据结构


C++数据结构——栈

目录
1、简介
2、基本结构
3、基本操作


简介

栈是限制插入和删除只能在一个位置上进行的表,该位置是表的末端,叫做栈的顶,栈的特点是先进后出(后进先出)

基本结构

栈的基本结构如下图

我们可以发现其实栈的结构图横过来看就是一张使用了头插法的表,所以我们在创建时按照表的创建方法就行了

基本操作

栈的基本操作只有入栈和出栈两个操作

栈的类型声明

typedef struct node* Node;
struct node{
	int Element;
	Node next;
};

入栈

void push(Node head,int x){
	Node temp=new node;
	temp->Element=x;
	temp->next=head->next;
	head->next=temp;
}

出栈

void pop(Node head){
	if(head->next){
		Node temp=new node;
		temp=head->next;
		head->next=temp->next;
		delete(temp);
	}
}

这些操作与表那一节一模一样,如果有不懂的可以看我之前的博客

下面贴上完整代码

#include<iostream>
using namespace std;
typedef struct node* Node;
struct node{
	int Element;
	Node next;
};
void push(Node head,int x){//传入参数节点要是头结点
	Node temp=new node;
	temp->Element=x;
	temp->next=head->next;
	head->next=temp;
}
void pop(Node head){//传入参数节点要是头结点
	if(head->next){
		Node temp;
		temp=head->next;
		head->next=temp->next;
		delete(temp);
	}
}
void print(Node head){
	while(head->next){
		cout<<head->next->Element<<" ";
		head=head->next;
	}
}
//输入五个数,入栈后出一次栈,然后输出
int main(){
	int x;
	Node head=new node;
	head->next=NULL;
	for(int i=0;i<5;i++){
		cin>>x;
		push(head,x);
	}
	pop(head);
	print(head);
	return 0;
}

有什么遗漏或者错误,欢迎大家指出

标签:Node,node,head,temp,int,C++,next,数据结构
来源: https://www.cnblogs.com/yszcode/p/13687609.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有