c++

I am having trouble understanding how the push and pop works with stacks. I understand how they work as in they push a number let's say onto the stack and the last number pushed on would be popped off. I also understand the logic behind pointers and how they work. What I do not understand is how the code is supposed to be written.

My program is supposed to let the user create a stack (determine how large it is) and then choose to push memory (numbers) on the stack or pop them off.

Here is what I got so far and I am stuck. I have researched through cplusplus.com and read pretty much everything about this stuff but still cannot figure out how the program is supposed to be laid out and how it runs.

#include<iostream>
#include<cstring>
#include<cmath>
#include<cstdlib>

using namespace std;

int choice;
int * arrPtr = NULL;
int * stack;
int * top;
int val, capacity, size; 
//stack would point to the location of the first element,
// top would point to the location where the next element will be stored,
// capacity is the number of elements that can be stored in the stack,
// size would be the number of elements actually stored in the stack

int main()
{
//This is the menu
cout << "1. Create" << endl;
cout << "2. Push" << endl;
cout << "3. Pop" << endl;
cout << "4. Count" << endl;
cout << "5. Display" << endl;
cout << "6. Exitn" << endl;
cin >> choice;

//I figured i would use choices for the menu and went ahead and wrote it out
switch(choice)
{
    case 1:
        create();
        break;
    case 2:
        push();
        break;
    case 3:
        pop();
        break;
    case 4:
        count(0);
        break;
    case 5:
        display();
        break;
    case 6:
        exit();
    default:
        cout << "Please enter correct choice (1-4)!";
        break;
    }

    return 0;   
}   //end main

void create()
{
    cout << "Enter the size of the stack you wish to create: ";
    int capacity = 0;
    cin >> capacity;

    arrPtr = new int[capacity];
} //end create function

//From here it went wrong, I cannot figure it out.           

void push(){
    for (int i = 0; i < capacity; i++)
    {
        cout << "Enter the number you wish to put on the stack: ";
        cin >> val;
        push(val)
    }//end for
}//end push

Please, help me understand this.


Create std::array . Create iterator. Set iterator to the end of array. (end meaning array.end() )

Push: decrement iterator, insert value.
Pop: return value, increment iterator.
Count: not standard on stacks, but you can get it by subtracting current iterator from end.
Peek: return value

Obviously you want to make sure you're not pushing off of the front of the array, or popping off of the back, so you should add some checks.

Stacks are really simple. Hope this helps.

EDIT: Implementations, untested code ahead, kinda stream-of-thought'ing this

template <typename T, std::size_t N>
class Stack {
public:
  Stack();
  void push(T value);
  T pop();
  T peek() const;
  std::size_t count() const;

private:
  std::array<T, N> m_baseArray;
  std::array<T>::iterator m_it;
};

template <typename T, std::size_t N>
Stack::Stack() : m_baseArray(), m_it(m_baseArray.end()) { }

template <typename T, std::size_t N>
void Stack::push(T value) {
  if (m_it == m_baseArray.begin())
    throw std::exception();
  --m_it;
  *m_it = value;
}

template <typename T, std::size_t N>
T Stack::pop() {
  if (m_it == m_baseArray.end())
    throw std::exception();
  T res = *m_it;
  ++m_it;
  return res;
}

template <typename T, std::size_t N>
T Stack::peek() const {
  if (m_it == m_baseArray.end())
    throw std::exception();
  return *m_it;
}

template <typename T, std::size_t N>
std::size_t Stack::count() const {
  return m_baseArray.end() - m_it;
}

最简单的堆栈使用std::vector

#include <iostream>
#include <vector>
using namespace std;

template<typename T>
class Stack{
private: 
  vector<T> theArray;
public:
  Stack(){ theArray.clear(); }
  void push(T data) { theArray.push_back(data); }
  T pop() { T retData = theArray.back(); theArray.pop_back(); return retData; }
  void display() {
    for(size_t i = theArray.size() - 1; i != (size_t)-1; i--){
      cout << theArray[i] << 'n';
    }
  }
};

int main(int argc, char *argv[])
{
  Stack<int> s;
  s.push(10);
  s.push(20);
  s.push(30);
  s.display();

  int ret = s.pop();
  cout << "After popping : " << ret << 'n';
  s.display();
  return 0;
}

我已经在Mac上编译了这些代码,但它应该在装有bash的PC上的Linux上正常工作。

#include<iostream>
#include<cstring>
#include<cmath>
#include<cstdlib>

using namespace std;

int choice;
int capacity; /*size of stack*/ 

int stack[1000];/*THIS IS WHERE ALL THE STACK ENTRIES WILL BE STORED*/
int top=0; /* THIS WILL KEEP CHECK OF THE INDEX OF TOP MOST ELEMENT */

//stack would point to the location of the first element,
// top would point to the location where the next element will be stored,
// capacity is the number of elements that can be stored in the stack,
// size would be the number of elements actually stored in the stack

void create() //Set size of stack
{
    cout << "Enter the size of the stack you wish to create: ";
    cin >> capacity;

} //end create function


void push(int n) //Enter data into stack

{

/* Ensures that there isn't a stack overflow */

    if(top<capacity)
    {
        stack[top++]=n; 
    }


    else
    {
        cout<<"Stack FULL!!n";
    }

    //end for
}//end push

void pop() //Remove data from stack
{
    /* Ensures that there isn't a stack underflow */
    if(top>0)
    {
        cout<<"Popped entry is:"<<stack[top-1]<<"n";
        top--;   
    }

    else
    {
        cout<<"Stack is EMPTY!!n";
    }


}

void count() //Count number of elements
{
    cout<<"Stack size is:"<<top<<"n"; 
}

void display() //Print elements from lowest stack entry to highest 
{
    int i=0;
    cout<<"Your stack is:n";
    while(i<top)
    {
        cout<<i+1<<") "<<stack[i]<<"n";
        i++;
    }
}



int main()
{
    system("clear");  //Start with blank screen



    int exitCheck=1,entry;

    //I figured i would use choices for the menu and went ahead and wrote it out -- This is good approach!!
    cout<<"Welcome user n";

    create(); /*Size of stack can be set only once to prevent inconsistency */

    while(exitCheck == 1)  /* This is the menu */
    {

        cout << "1. Push" << endl;
        cout << "2. Pop" << endl;
        cout << "3. Count" << endl;
        cout << "4. Display" << endl;
        cout << "5. Exitn" << endl;
        cin >> choice; //Choice should be placed here as we need userinput during each turn 

        switch(choice)
        {
            case 1:
                cout<< "Enter your data: ";
                cin>>entry;
                push(entry);
                break;
            case 2:
                pop();
                break;
            case 3:
                count();
                break;
            case 4:
                display();
                break;
            case 5:
                {
                    exitCheck=1;
                    break;
                } /*exit in this case wont achieve a proper result in a concole based app thats why i replaced it with loop exit condition */

            default:
                cout << "Please enter correct choice (1-5)!n";
                break;
            }

        cout<< "Enter 1 to continue else anything else to quit:n";
        cin>> exitCheck;


    }

    cout<<"Thanks for using this code!!n";    
return 0;   
}
  //end main
链接地址: http://www.djcxy.com/p/84346.html

上一篇: 中缀到Postfix转换错误

下一篇: C ++