【发布时间】:2016-02-18 04:48:38
【问题描述】:
所以我正在使用链表实现一个堆栈类,我需要将一个字符串推入堆栈,但堆栈只能保存整数。我正在尝试将字符串拆分为整数并将它们中的每一个都推入堆栈但没有骰子。
#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;
}
【问题讨论】:
-
改变你的类,让堆栈保存字符串?
-
使用“模板”关键字参数化类型上的类。
-
请创建清晰的问题陈述、预期和实际结果以及重现它所需的最短代码。
-
您将
Input.size()的atoi(Input.c_str())副本推送到您的堆栈中。如果Input是123,那么您的堆栈现在是{123, 123, 123}。这是你的意图吗? -
不,我需要它是 {1, 2, 3}
标签: c++ data-structures linked-list stack