行编辑程序问题:
输入字符串,当遇到#字符时,自动撤回注销前一个字符,从而实现编辑字符串功能。
#include <stdio.h>
#include <stdio.h>
#include <iostream>
using namespace std;
#define sElemType char
typedef struct linkNode{
sElemType data;//数据域
linkNode *next;//指针域
}*linkStack;
//判空函数(链栈为空返回1;不为空返回0)
int isEmpty(linkStack top){
return top==NULL;
}
//初始化链栈
void initLinkStack(linkStack &top){
top=NULL;
}
//插入元素到链栈
void push(linkStack &top,sElemType val){
linkStack newNode=new linkNode[1];
newNode->data=val;
newNode->next=top;
top=newNode;
}
//删除链栈的栈顶元素
void pop(linkStack &top,sElemType &val){
if(isEmpty(top)){
return;
}
val=top->data;
linkStack tempPtr=top;
top=top->next;
delete tempPtr;
}
void lineEdit(char *str){
linkStack top1;
initLinkStack(top1);
linkStack top2;
initLinkStack(top2);
int i=0;
while('\0'!=str[i]){
if('#'!=str[i]){
push(top1,str[i]);
}
else if('#'==str[i]) {
sElemType e;
pop(top1,e);
}
i++;
}
//为了使字符串正序输出,需要两个栈从而实现正序输出
while(!isEmpty(top1)){
sElemType e;
pop(top1,e);
push(top2,e);
}
while(!isEmpty(top2)){
sElemType e;
pop(top2,e);
cout<<e;
}
}
int main(){
char str[100];
cin>>str;
lineEdit(str);
} 在这里插入代码片
运行结果截图: