【发布时间】:2015-05-24 10:52:11
【问题描述】:
打印 removeDuplicates 函数返回的新堆栈时出现无限循环,但我不知道是什么原因造成的?所有其他功能都运行良好。如果元素重复,函数应保留第一次出现。这是代码:
class Stack {
Node *head;
public: Stack() {
head = NULL;
};
~Stack() {
while (head) {
Node * temp = head;
head = head->next;
delete temp;
}
}
void push(int data);
int pop();
bool isEmpty();
void print();
Stack removeDuplicates();
};
void Stack::push(int data) {
Node *temp = new Node(data);
temp->next = head;
head = temp;
}
int Stack::pop() {
if (head != NULL ) {
int x = head->data;
Node *temp = head;
head = head->next;
delete temp;
return x;
} else {
cout << "The stack is empty!";
return -1;
}
}
bool Stack::isEmpty(){
return head == NULL;
}
void Stack::print() {
Node * temp = head;
while(temp != NULL ) {
cout << temp->data << " ";
temp = temp->next;
}
}
Stack Stack::removeDuplicates(){
Stack st;
Node *temp = NULL;
bool flag;
while (head != NULL) {
if (st.head == NULL) {
st.push(head->data);
temp = st.head;
} else {
flag = true;
while (temp != NULL) {
if (head->data == temp->data)
flag = false;
temp = temp->next;
}
if (flag == true)
st.push(head->data);
}
Node *del = head;
head = head->next;
delete del;
}
return st;
}
【问题讨论】:
-
请告诉我您尝试过使用调试器进行单步调试。
-
@AtlasC1 :
st.headvshead? -
@AtlasC1 'st.head' 是新堆栈的头部;而 'head' 是原始堆栈的头.. 那会导致错误吗?
-
@norisknofun 'st.head' 是新堆栈的头部;而“头”是原始堆栈的头..?
-
为什么不直接发布与堆栈相关的所有代码并干净地格式化它,这样人们就可以真正看到发生了什么而不是猜测变量?当所有上下文都可用时,很难调试。
标签: c++ stack infinite-loop