数据结构-链栈
来源:互联网 发布:java 注释 link 编辑:程序博客网 时间:2024/06/06 06:31
链式存储的栈称为链栈,结构如下图:
链栈无满栈问题,空间可扩充,但有栈空问题,栈空的条件为top->next==NULL。进栈与入栈仅在栈顶进行,链式栈的栈顶在栈表头。链栈的定义如下:
struct StackNode { int data; //结点数据 StackNode *next; //结点链指针};class Stack{ StackNode *top; //栈顶指针public: Stack() { top=new StackNode; top -> next = NULL; } //创建头结点 ~Stack() { delete top; } void Push(int item); //入栈 int Pop(); //出栈 int GetTop(); //获取栈顶元素 void Clear(); //清空栈 bool IsEmpty() { return top->next == NULL; } //判断栈是否为空 void Transform(long N, int d); //数制转换};
类中具体的算法实现如下:
//入栈操作void Stack::Push(int item) { StackNode *p; //新建一结点 p = new StackNode; p->data = item; p->next = top->next; top->next = p;}//出栈操作int Stack::Pop(){ StackNode *p; if (top->next!=NULL) { p = top->next; int retvalue = p->data; //暂存栈顶数据 top->next = p->next; //修改栈顶指针 delete p; return retvalue; //释放,返回数据 }else { cout<<"the stack is empty!"<<endl; exit(0); }}//获取栈顶元素操作int Stack::GetTop(){ if (top->next!=NULL) { return top->next->data; }else { cout<<"the stack is empty!"<<endl; exit(0); }}void Stack::Clear(){ StackNode *p; while (top->next!=NULL) { p = top->next; top->next = p->next; //修改栈顶指针 delete p; }}
栈的应用–数制转换(十进制转d进制):
void Stack::Transform(long N, int d){ Stack s; cout<<N; while (N!=0) { int k = N%d; s.Push(k); N = N/d; } cout<<"的"<<d<<"进制数为:"; while (!s.IsEmpty()) { cout<<s.Pop(); } cout<<endl;}
在主函数进行具体的数据操作:
int main() { Stack stack; stack.Push(12); stack.Push(23); stack.Pop(); int t = stack.GetTop(); bool b = stack.IsEmpty(); cout<<b<<endl; cout<<t<<endl; stack.Transform(4587,8); //转八进制 return 0;}
0 0
- 数据结构-链栈
- 【数据结构】链栈
- 《数据结构》链栈
- 数据结构-链栈
- 数据结构--链栈
- 数据结构-链栈
- 数据结构--链栈
- 【数据结构】链栈_LinkStack
- 数据结构与算法--链栈
- 数据结构_链栈
- 数据结构 - 链栈(C)
- 数据结构——链栈
- C语言数据结构-链栈
- 数据结构2链栈
- 数据结构-链栈(C语言)
- 数据结构 -- 链栈java实现
- C语言-数据结构-链栈
- C数据结构-链栈
- Google 面试题 | 判断字符串是否可由重复子字符串组成
- MFC CFolderPickerDialog 和CFileDialog选择文件路径
- Composite模式
- 时间显示格式
- 查看SELinux状态
- 数据结构-链栈
- angularjs生命周期的compile的 pre-link阶段都干了什么
- SQL_基础篇
- android各大手机系统打开权限管理页面
- Java通过反射调用方法
- Streamsql&&Kafka demo
- STM32的以太网MAC设置
- Ruby on Rails学习笔记(二 )
- 多核处理器内存模型