I'd suggest different classes for the stack, the nodes referencing/holding the data and the data (items) themselves. If that all works, then work on the code. Is the stack state correct? If so, now pop off all of the 3 items, one at a time, and again move the arrows (pointers) and verify that everything behaves correctly, especially in the case of popping off the last item (because that's where you currently are having trouble). Erase and redraw the pointers as they change. To debug your algorithm (not the code, the algorithm if this isn't correct, the code will never be correct) I'd take a pencil and paper and walk through the steps of pushing 3 items onto the stack: draw boxes to represent the stack nodes and arrows to represent the pointers. If your objective is just to implement a stack (LIFO queue), then a doubly-linked list is more complexity than you want.Ī stack can be implemented with a singly linked list. We will use a Node object which will be storing the element and the reference to the next and the previous element.As nv3 pointed out in Solution 1, using the same class for the stack and for the items you are managing is leading to confusion. singly linked list Push insert at front of list Pop delete at the front of list Top examine element at the front no limit on the size of stack. Implementing a doubly linked list in javascript
0 Comments
Leave a Reply. |