所以我使用链表实现堆栈类,我需要将一个字符串压入堆栈,但堆栈只能保存整数。我试图将字符串分成整数并将它们中的每一个推入堆栈但没有骰子。
#include<iostream>
#include<string>
using namespace std;
class Stack {
public:
Stack() {
top = NULL;
count = 0;
size = 0;
}
void push(int numberToPush) {
//create a new linkedlistnode assing its value to number to push
//and add it to the underlying linkedlist structure
LinkedListNode *n = new LinkedListNode;
n -> val = numberToPush;
n -> next = top;
top = n;
size++;
}
int pop() {
//returns value of the node at the top of the stack and removes the node
if(isEmpty()) {
cout << "stack is empty pop" << endl;
return -1;
}
LinkedListNode *temp = top;
top = temp -> next;
return temp -> val;
}
int peek() {
//returns the value of the node at the top of the stack, but does not remove the node
if(isEmpty()) {
cout << "stack is empty" << endl;
return -1;
}
return top -> val;
}
void display() {
LinkedListNode *n = top;
for(int i = 0; i < size; i++) {
cout<< top->val << ", ";
top=top->next;
}
}
bool isEmpty() {
return top == NULL;
}
private:
struct LinkedListNode {
int val;
LinkedListNode *next;
};
LinkedListNode* top;
int count;
int size;
};
int main() {
string Input;
cout << "enter a word or phrase: ";
cin >> Input;
Stack s;
for(int i = 0; i < Input.length(); i++)
s.push(Input[i]);
s.display();
return 0;
}
答案 0 :(得分:-1)
for(int i = 0; i < Input.size(); i++) {
a = atoi(Input.c_str());
s.push(a);
}
我不认为这段代码正在做你认为它正在做的事情。 atoi()将一个字符串转换为一个int,即“76”变为76.你好像想要字符串中每个字符的ASCII值,代码看起来更像是这样:
for(int i = 0; i < Input.size(); i++) {
a = (int)Input[i];
s.push(a);
}
请注意,这会在Stack中创建n个不同的元素,每个元素对应一个字符串。如果你需要在堆栈中添加除整数之外的东西,你应该为你的类创建一个模板,而不是像这样来回转换。