链栈.cpp

来自「在学习数据结构的时候要用到栈」· C++ 代码 · 共 52 行

CPP
52
字号
#include<iostream.h>
#include<stdlib.h>
//定义链栈结构
typedef struct node
{
	char data;
	struct node *next;
}seqstack;
typedef seqstack *stack;

//栈的初始化
int initstack(stack &top)
{
   
    top=(seqstack *)malloc(sizeof(seqstack));
	top->next=0;return(1);
}

//链栈的进栈操作
int push(stack &top,int x)
{
	seqstack *p;
	p=(seqstack *)malloc(sizeof(seqstack));
	if(p==NULL)  return 0;
    p->data=x; p->next=top->next;
	top->next=p;   
	return 1;
}

//链栈的出栈操作
int pop(stack top,int &x)
{
	seqstack *p;
	p=top->next;
	    if(p==NULL)  /*栈为空*/
	    return(0);
  top->next=p->next; 
  x=p->data;
     free(p);   /* 释放存储空间 */
     return(x);
}
void main()
{
	stack top;
	int x;
	initstack(top);
	push(top,2);
    push(top,3);
	pop(top,x);cout<<x<<endl;
	pop(top,x);cout<<x<<endl;
		  
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?