Thursday, March 11, 2010

a question about stack

in class we learned how S.pop() delete data in stack. My question is that whether we should delete data in reverse order?

S.push(Student("Fardad", "oop344", 56));

S.push(Student("John", "int322", 100));
S.push(Student("Jack", "int422", 90));
S.pop();
S.pop();
while(!S.IsEmpty()){
cout< }
Student StdStack::pop(){
Student ret = top->data;
Node* ToDel = top;
top = top->next;
delete ToDel;
return ret;
}
the output is Fardad, oop344: 56

i read some material in btp300
Element pop() {
Element data;
if (head) {
Node* p = head;
data = head->data;
head = head->next;
delete p;
}
return data;
}

Stack s;

// Push Data Onto Stack
s.push(3);
s.push(5);
s.push(9);
s.push(8);

// Remove first Node
s.pop();

// Pop Data Off Stack
while (!s.empty())
cout << s.pop().out() << ' ';
cout << endl;

the output is 9 5 3

could any one explain the difference between this two example why the pop() are different?

2 comments:

  1. I don't think there is a difference. Fardad's example popped twice before the loop so the only item left is 56.
    Basically:
    original stack(top item is top of stack):
    90
    100
    56

    so after one pop it would be:
    100
    56

    after 2nd pop

    56



    Your example popped only once before output so 9,5 and 3 was left.

    Your stack after pushing 4 numbers:
    8
    9
    5
    3

    after the first pop
    9
    5
    3

    then you popped in a loop and did output as you went, removing 9, 5, 3 in that order


    Stacks by definition is FILO. so the earlier something was added the later it is removed.

    ReplyDelete
  2. Yes, cathyatseneca is right. Stack works the way of First in Last out (FILO). However, linked list works another way, FIFO, means First in First out.

    ReplyDelete