CCCCCCC123456789
2020-03-16 16:39
采纳率: 66.7%
浏览 161

C++ prime plus 第十章书上上的栈是如何实现的?

代码:
// stack.h -- class definition for the stack ADT
#ifndef STACK_H_
#define STACK_H_

typedef unsigned long Item;

class Stack
{
private:
enum {MAX = 10}; // constant specific to class
Item items[MAX]; // holds stack items
int top; // index for top stack item
public:
Stack();
bool isempty() const;
bool isfull() const;
// push() returns false if stack already is full, true otherwise
bool push(const Item & item); // add item to stack
// pop() returns false if stack already is empty, true otherwise
bool pop(Item & item); // pop top into item
};
#endif

// stack.cpp -- Stack member functions
#include "stack.h"
Stack::Stack() // create an empty stack
{
top = 0;
}

bool Stack::isempty() const
{
return top == 0;
}

bool Stack::isfull() const
{
return top == MAX;
}

bool Stack::push(const Item & item)
{
if (top < MAX)
{
items[top++] = item;
return true;
}
else
return false;
}

bool Stack::pop(Item & item)
{
if (top > 0)
{
item = items[--top];
return true;
}
else
return false;
}

// stacker.cpp -- testing the Stack class
#include
#include // or ctype.h
#include "stack.h"
int main()
{
using namespace std;
Stack st; // create an empty stack
char ch;
unsigned long po;
cout << "Please enter A to add a purchase order,\n"
<< "P to process a PO, or Q to quit.\n";
while (cin >> ch && toupper(ch) != 'Q')
{
while (cin.get() != '\n')

continue;
if (!isalpha(ch))
{
cout << '\a';
continue;
}
switch(ch)
{
case 'A':
case 'a': cout << "Enter a PO number to add: ";
cin >> po;
if (st.isfull())
cout << "stack already full\n";
else
st.push(po);
break;
case 'P':
case 'p': if (st.isempty())
cout << "stack already empty\n";
else {
st.pop(po);
cout << "PO #" << po << " popped\n";
}
break;
}
cout << "Please enter A to add a purchase order,\n"
<< "P to process a PO, or Q to quit.\n";
}
cout << "Bye\n";
return 0;
}

我主要是疑问的地方是:
bool Stack::pop(Item & item)
{
if (top > 0)
{
item = items[--top];
return true;
}
else
return false;
}
这个函数怎么把栈顶的数据给移除啊, item = items[--top]只是修改了参数,没有改变栈顶啊。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • 时光放逐 2020-03-16 17:12
    已采纳

    --top表示元素数目减一即移动了栈顶,比如之前top = 7 栈顶元素为items[6] 现在top = 6 并将items[6]赋给item, 此时栈顶为items[5];
    至于items[6]处的数据,并不需要移除,下一次入栈到这个位置会将原来的值覆盖

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题