无限循环,从堆栈中删除重复项?

时间:2015-03-20 22:07:53

标签: c++ stack infinite-loop

在打印由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;
 }

1 个答案:

答案 0 :(得分:0)

什么是声明在函数之外的头?

该函数外的任何代码是否修改头?

如果head为null进入函数,那么你的函数不会做任何事情,并且根据你也没有出现的打印代码,它可能只是因为这个原因而永远循环。

在你的第一个if语句中你有if(st.head == NULL)...然后你将temp设置为st.head,例如temp = NULL,那么什么时候temp在if语句的else分支中使用非null?

为什么不在函数内部显式初始化所有变量,而不是仅仅声明它们并将它们与类型相关联,因为如果它们是堆栈变量,则它们是未定义的。如果您对代码进行格式化,它也有助于理解和维护代码,以便更容易直观地解析。你会惊讶地发现你可以从这个学科中捕获多少错误。

  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)
               st.push(head->data);
        }
        Node *del = head;
        head = head->next;
        delete del;
     }
     return st;
  }