一.描述
从键盘输入一行字符,进入链栈,以回车符结束.通过链栈的出栈操作实现该行字符的反向输出.
二.代码部分
2.1 stacklist.h头文件
#pragma once
#include<iostream>
using namespace std;
typedef struct listStack {
char data;
struct listStack * next;
}listStack;
//入栈操作
listStack* push(listStack * stack, char a) {
listStack * line = (listStack*)malloc(sizeof(listStack));
line->data = a;
line->next = stack;
stack = line;
return stack;
}
//出栈操作
listStack * pop(listStack * stack) {
if (stack) {
listStack * p = stack;
stack = stack->next;
cout << p->data;
if (stack == NULL) {
cout << endl;
printf("栈已空\n");
}
free(p);
}
else {
printf("栈内没有元素");
return stack;
}
return stack;
}
//取得栈顶元素
char top(listStack* stack) {
char ele;
listStack* p;
p = stack;
if (!p) {
cout << "栈已空" << endl;
return 0;
}
ele = p->data;
return ele;
}
//判断栈的大小
int size(listStack* stack) {
listStack* p = NULL;
int count = 0;
p = stack;
while (p != NULL) {
p = p->next;
count++;
}
return count;
}
//判断栈是否为空
bool isEmpty(listStack* stack) {
if (stack == NULL) {
return true;
}
return false;
}
2.2 main函数
#include<iostream>
#include<string>
#include "stacklist.h"
using namespace std;
int main() {
while (true) {
listStack* stack = NULL;
cout << "输入字母;" << endl;
string str;
getline(cin, str);
cout << "栈是否为空:" << isEmpty(stack) << endl;
for (int i = 0; i < str.length(); i++) {
stack = push(stack, str[i]);
}
cout << "栈是否为空:" << isEmpty(stack) << endl;
cout << "栈顶元素:" << top(stack) << endl;
cout << "目前栈的大小:" << size(stack) << endl;
cout << "输出倒序:" << endl;
for (int i = 0; i < str.length(); i++) {
stack = pop(stack);
}
}
return 0;
}