c++ - Infinite loop, removing duplicates from a stack? -
i infinite loop when printing new stack that's returned removeduplicates function, don't know what's causing it? other functions working perfectly. functions should keeps first occurrence if element duplicated. code:
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 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; }
what head declared outside function?
does code outside function modify head?
if head null going function function won't anything, , depending on print code didn't present, might loop forever reason alone.
in first if statement have if (st.head == null) ... , set temp st.head, e.g. temp = null, when temp ever going non-null use in else branch of if statement?
why don't initialize variables explicitly inside function instead of merely declaring them , associating them types, since, if they're stack variables undefined. helps understand , maintain code if format easier parse visually. you'd surprised how many errors can catch 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; }
Comments
Post a Comment