Stack Operations With Linked LIst in Java -
i have write class should implement stack using linked list. however, should perform push , pop operations tail of list instead of head. furthermore, should not maintain reference list’s tail node.
how on earth achieve without keeping reference last node??
you could pretty inefficient because have go through entire list every time want something. there isn't reason why want keep reference head while operations performed @ tail.
but here's how anyway:
class entry<e> { e object; entry<e> next; public entry(e obj) { object = obj; } } class stacklist<e> { entry<e> head; public void push(e element) { if (head == null) { // first head = new entry<e>(element); return; } entry<e> node = head; while (node != null && node.next != null) { node = node.next; } // node tail entry<e> newentry = new entry<e>(element); node.next = newentry; } public e pop() { if (head == null) { // empty return null; } entry<e> node = head, previousnode = null; while (node.next != null) { previousnode = node; node = node.next; } // node tail // previousnode next-to-last if (previousnode != null) { previousnode.next = null; } else { // there 1 thing head = null; } return node.object; } }
Comments
Post a Comment