【问题标题】:pushing values to stack class using linked list struct c++使用链表struct c ++将值推送到堆栈类
【发布时间】: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()) 副本推送到您的堆栈中。如果 Input123,那么您的堆栈现在是 {123, 123, 123}。这是你的意图吗?
  • 不,我需要它是 {1, 2, 3}

标签: c++ data-structures linked-list stack


【解决方案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 个不同的元素,每个元素对应于字符串中的每个字符。如果您需要将整数以外的东西添加到您的堆栈中,您应该为您的类创建一个模板,而不是像这样来回转换。

【讨论】:

  • 这个可以用整数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-15
  • 2023-03-24
  • 1970-01-01
相关资源
最近更新 更多