菜单驱动的程序,堆栈为带字符信息的链表
menu driven program for stack as linked list with char info
作为学校数据结构作业的一部分,我必须编写一个程序来实现Stack作为链表。下面是我写的代码。
C++程序使用链表实现堆栈
#include<iostream.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
/*
* Node Declaration
*/
struct node
{
char city[20];
struct node *link;
}*top;
/*
* Class Declaration
*/
class stack_list
{
public:
node *push(node *, char[20]);
node *pop(node *);
void traverse(node *);
stack_list()
{
top = NULL;
}
};
/*
* Main: Contains Menu
*/
int main()
{
int choice;
char item[20];
stack_list sl;
do
{
cout<<"n-------------"<<endl;
cout<<"Operations on Stack"<<endl;
cout<<"n-------------"<<endl;
cout<<"1.Push Element into the Stack"<<endl;
cout<<"2.Pop Element from the Stack"<<endl;
cout<<"3.Traverse the Stack"<<endl;
cout<<"4.Quit"<<endl;
cout<<"Enter your Choice: ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter value to be pushed into the stack: ";
gets(item);
top = sl.push(top, item);
break;
case 2:
top = sl.pop(top);
break;
case 3:
sl.traverse(top);
break;
case 4:
exit(1);
break;
default:
cout<<"Wrong Choice"<<endl;
}
} while(choice !=4);
return 0;
}
/*
* Push Element into the Stack
*/
node *stack_list::push(node *top, char city[20])
{
node *tmp=NULL;
tmp = new (struct node);
strcpy(tmp->city,city);
// tmp->city[20] =item[20];
tmp->link = top;
top = tmp;
return top;
}
/*
* Pop Element from the Stack
*/
node *stack_list::pop(node *top)
{
node *tmp;
if (top == NULL)
cout<<"Stack is Empty"<<endl;
else
{
tmp = top;
cout<<"Element Popped: "<<tmp->city<<endl;
top = top->link;
free(tmp);
}
return top;
}
/*
* Traversing the Stack
*/
void stack_list::traverse(node *top)
{
node *ptr;
ptr = top;
if (top == NULL)
cout<<"Stack is empty"<<endl;
else
{
cout<<"Stack elements :"<<endl;
while (ptr != NULL)
{
cout<<ptr->city[20]<<endl;
ptr = ptr->link;
}
}
}
以下程序在运行过程中不显示推送的字符。如果我推"Delhi",我会被推和弹出,但当我称之为横向时,它不会显示被推的成员。
此行错误:
cout<<ptr->city[20]<<endl;
您需要使用:
cout<<ptr->city<<endl;
建议更改stack_list
在类中创建一个成员变量top
,而不是使用全局top
。然后,您可以简化成员函数。他们不再需要node*
作为输入。
class stack_list
{
public:
node *push(char[20]);
node *pop();
void traverse();
stack_list()
{
top = NULL;
}
private:
node* top;
};
相应地更改实现。
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 为什么 Serial.println(<char[]>);返回随机字符?
- 我的字符计数代码计算错误.为什么
- 字符串-C++后显示的随机字符
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 如何在C++中从字符串中分割字符
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 指向指向字符数组的指针数组的指针
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 如何用转义符替换字符串中的所有特殊字符
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 按字母顺序打印存储在字符数组中的信息
- 将文件信息(字符数组)嵌入到编译的二进制文件中
- 从地图中获取字符分类信息时出现问题
- 菜单驱动的程序,堆栈为带字符信息的链表
- 将文本信息从 Windows 命令解释器 (cmd.exe) 管道到字符数组
- 如何确定unicode字符的字体和布局信息