我有一个基于用户输入动态创建的列表。我可以添加字符串,我可以删除字符串,但我不知道如何正确地反向打印它。
实施例: 输入:第一秒钟 输出:最后一秒
我已经尝试了一些事情,我已经查找了需要做的事情,但我很难把它弄清楚。
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
// define a node for storage and linking
class node{
public:
string name;
node *next;
node *prev;
};
class linkedList{
public:
linkedList() :top(NULL){}
bool empty(){ return top == NULL; }
node *getTop(){ return top; }
void setTop(node *n){ top = n; }
void add(string);
int menu();
void remove(string);
~linkedList();
void reversePrint();
friend ostream& operator << (ostream&, const linkedList&); // default
output is in-order print.
private:
node *top;
node *end;
};
void main(){
linkedList l;
cout << l.empty() << endl;
int option = 0;
string s;
bool go = true;
while (go){
option = l.menu();
switch (option){
case 1: cout << "enter a name: "; cin >> s; l.add(s); break;
case 2: cout << "enter name to be deleted: "; cin >> s; l.remove(s); break;
case 3: cout << l; break;
case 4: cout << l.reversePrint(); break; // I am getting a Syntax error here
case 5: cout << "exiting" << endl; go = false; break;
}
}
system("PAUSE");
// l goes out of scope and calls ~linkedList()
}
void linkedList::reversePrint()
{
node *start_ptr = NULL;
node *current = start_ptr;
node *prev = NULL;
node *next = NULL;
while (current){
next = current->next;
current->next = prev;
current->prev = next;
prev = current;
current = next;
}
}
答案 0 :(得分:0)
您没有提供完整的代码(例如linkedList :: add()的实现),因此很难给出正确的答案......
根据您的部分代码,由于reversePrint()的返回类型为void,因此您无法进行cout。 因此,在主要功能的开关块中应该是:
case 4: l.reversePrint(); break;
我尝试修改你的代码,但不确定它是否正确,因为我没有代码。
void linkedList::reversePrint()
{
node *current = end;
while (current){
cout << current->name << " ";
current = current->prev;
}
}