【发布时间】:2012-10-25 16:59:49
【问题描述】:
好的,我正在尝试使用链表为我的 C++ 作业编写堆栈弹出方法。 让我先告诉你节点和列表类,然后告诉你问题:
class Node
{
public:
int data;
Node* next;
Node(int data, Node* next = 0)
{
this->data = data;
this->next = next;
}
};
class List
{
private:
Node* head; // no need for the tail when using the list for implementing a stack
public:
List()
{
head = 0;
}
void add_to_head(int data)
{
if(head == 0)
{
head = new Node(data);
}
else
{
head = new Node(data, head);
}
}
Node* get_head()
{
return head;
}
// this deletes the head element and makes 'head' points to the node after it.
void delete_head()
{
// storing the head so that we could delete it afterwards.
Node* temp = head;
// making the head point to the next element.
head = temp->next;
// freeing memory from the deleted head.
delete(temp);
}
};
现在是堆栈:
class stack
{
private:
List* list;
public:
stack()
{
list = new List();
flush();
}
void push(int value)
{
list->add_to_head(value);
}
bool pop(int& value_to_fill)
{
if(is_empty())
{
return false; // underflow...
}
value_to_fill = list->get_head()->data;
// deleting the head. NOTE that head will automatically point to the next element after deletion
// (check out the delete_head definition)
list->delete_head();
return true; // popping succeed.
}
bool peek(int& value_to_fill)
{
if(is_empty())
{
return false;
}
value_to_fill = list->get_head()->data;
return true;
}
// other stuff...
};
现在问题在于 pop 和 peek,我只是觉得它们不方便。 不应为 pop 和 peek 提供任何参数,但如果我这样做:
int peek()
{
if(is_empty())
// what should I do here?
return list->get_head()->data;
}
int pop()
{
if(is_empty())
// same thing here.
// deleting the tos then returning it.
// I know this is not what the pop in the STL stack does, but I like it this way
int tos = list->get_head()->data;
list->delete_head();
return tos;
}
发生下溢时我不知道该怎么办。 我不能只返回 -1 或 0 或类似的东西,因为这看起来好像我弹出了 -1 或 0(tos == -1 或 0) 有没有一种方法可以编写防下溢 pop/peek 而无需通过引用传递任何内容?
【问题讨论】:
-
他们说例外很好。
-
您不想使用讨厌的列表吗?
-
@doublep:嗯,据我所知(来自 C#)你不能这样做: int peek() { try { return list->get_head()->data; } catch(...) {} } 你会得到一个错误,说所有路径都必须返回一些东西。但我只是在 C++ 中尝试过,它成功了!它编译没有任何错误。它不应该给我那个错误吗?
-
@Vexe 如果代码实际上采用了该路径,这只是 C++ 中的错误。编译器很难确定这一点,因此不需要错误消息。 (这称为未定义行为。)
标签: c++ stack stackunderflow