C++ 使用链表结构c+;将值推送到堆栈类+;

C++ 使用链表结构c+;将值推送到堆栈类+;,c++,data-structures,linked-list,stack,C++,Data Structures,Linked List,Stack,因此,我正在使用链表实现一个堆栈类,我需要将一个字符串推入堆栈中,但堆栈只能容纳int。我试图将字符串拆分为整数,并将它们中的每一个都推入堆栈,但没有骰子 #include<iostream> #include<string> using namespace std; class Stack { public: Stack() { top = NULL; count = 0; size = 0; }

因此,我正在使用链表实现一个堆栈类,我需要将一个字符串推入堆栈中,但堆栈只能容纳int。我试图将字符串拆分为整数,并将它们中的每一个都推入堆栈,但没有骰子

#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; 
}
#包括
#包括
使用名称空间std;
类堆栈{
公众:
堆栈(){
top=NULL;
计数=0;
尺寸=0;
}
无效推送(整数推送){
//创建一个新的linkedlistnode,将其值分配给要推送的编号
//并将其添加到底层linkedlist结构中
LinkedListNode*n=新建LinkedListNode;
n->val=数字推送;
n->next=顶部;
top=n;
大小++;
}
int-pop(){
//返回堆栈顶部节点的值并删除该节点
if(isEmpty()){
库特瓦尔;
}
int peek(){
//返回堆栈顶部节点的值,但不删除该节点
if(isEmpty()){
不能输入;
堆栈s;
对于(int i=0;i
for(int i=0;i
我不认为这段代码正在做您认为它正在做的事情。atoi()将字符串转换为int,即“76”变为76。您似乎想要字符串中每个字符的ASCII值,对于这些值,代码看起来更像这样:

 for(int i = 0; i < Input.size(); i++) {
      a = (int)Input[i];
      s.push(a);
 }
for(int i=0;i

请注意,这将在堆栈中创建n个不同的元素,字符串中的每个字符对应一个元素。如果需要向堆栈中添加除整数以外的内容,则应为类创建一个模板,而不是像这样来回转换。

更改类以使堆栈包含字符串?使用“模板”关键字来参数化类型上的类。请创建一个清晰的问题陈述、预期和实际结果,以及复制它所需的最短代码。您将
Input.size()
atoi(Input.c_str())
的副本推送到堆栈中。如果
Input
123
,则堆栈现在是
{123,123,123}
。这就是你想要的吗?不,我需要它是{1,2,3}整数。这个整数就可以了
 for(int i = 0; i < Input.size(); i++) {
      a = (int)Input[i];
      s.push(a);
 }