数据结构代码练习(二)栈

//Data 2018.07.03

//Coder Rebellion

//建立了一个带头节点的动态链表

#include<iostream>
#include"malloc.h"
using namespace std;


#define OK 1
#define ERROR 0


typedef struct Node
{
int data;
Node* next;
}Node,*Nodeptr;


typedef struct Stack
{
Node head;//栈的底 
Nodeptr top;//指向栈顶的指针 
}Stack;//定义栈 


int InitializeStack(Stack &S)//初始化栈 

S.head.data = 0;
S.head.next = (Nodeptr)malloc(sizeof(Node));
S.top = S.head.next; 
S.top->next = NULL;
}


int Push(Stack &S)//入栈 

cout<<"data to be pushed in:";
cin>>S.top->data;//给栈顶元素赋值 
S.top->next = (Nodeptr)malloc(sizeof(Node));//开辟新的存储空间 
S.top = S.top->next;//栈顶指针指向新开辟的位置 
S.top->data = 0;
}


void Print(Stack &S)//打印 
{
Nodeptr ranger = S.head.next;
while(ranger!=S.top)
{
cout<<ranger->data<<" ";
ranger= ranger->next;
}
cout<<endl;
}
int Pop(Stack &S)//出栈 
{
Nodeptr ranger = S.head.next;
while(ranger->next!=S.top)//找到栈顶指针的前一个结点 
{
ranger = ranger->next;
}
S.top = ranger;//栈顶指针下移 
S.top->data = 0;//栈顶元素数据域置零 
S.top->next =NULL;//栈顶元素指针域置空 
return OK;
}






int main()
{
Stack S;
InitializeStack(S);
int i;
for(i = 0;i<5;i++)
{
Push(S);
Print(S);
}
Pop(S);
Print(S);
Pop(S);
Print(S);
Pop(S);
Print(S);
return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值