[Solved] Infinite loop, removing duplicates from a stack?


What is head declared as outside the function?

Does any code outside the function modify head?

If head is null going into the function then your function won’t do anything, and depending on the print code you also didn’t present, it might just loop forever for just that reason alone.

In your first if statement you have if (st.head == NULL) … and then you set temp to st.head, e.g. temp = NULL, so when is temp ever going to be non-null to use in the else branch of the if statement?

Why don’t you initialize all your variables explicitly inside the function instead of merely declaring them and associating them with types, since, if they’re stack variables they are undefined. It also helps to understand and maintain code if you format it so it is easier to parse visually. You’d be surprised how many errors you can catch with that discipline.

  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;
  }

2

solved Infinite loop, removing duplicates from a stack?