/// <summary> /// Function to push an element to the stack /// </summary> /// <param name="myStack">Stack</param> /// <param name="newData">Integer which would be inserted in to stack</param> public void Push(MyStack myStack, int newData) { //Allocate DLLNode and put in data DLLNode newDllNode = new DLLNode(newData); //Since we are adding at the beginning, prev is always NULL newDllNode.prev = null; // link the old list off the new DLLNode newDllNode.next = myStack.head; //Increment count of items in stack myStack.count += 1; /* Change mid pointer in two cases * 1) Linked List is empty. * 2) Number of nodes in linked list is odd. */ if (myStack.count == 1) { myStack.mid = newDllNode; } else { myStack.head.prev = newDllNode; if ((myStack.count % 2) != 0) // Update mid if ms->count is odd. { myStack.mid = myStack.mid.prev; } } //move head to point to the new DLLNode. myStack.head = newDllNode; }
/// <summary> /// Function to pop an element from stack. /// </summary> /// <param name="ms">Stack List</param> /// <returns>The data it removed from the stack</returns> public int Pop(MyStack ms) { // Stack underflow if (ms.count == 0) { Console.WriteLine("Cannot pop as the stack is empty"); return(-1); } DLLNode head = ms.head; int item = head.data; ms.head = head.next; // If linked list doesn't become empty, update prev of new head as NULL if (ms.head != null) { ms.head.prev = null; } ms.count -= 1; // update the mid pointer when we have even number of elements in the stack, i,e move down the mid pointer. if (ms.count % 2 == 0) { ms.mid = ms.mid.next; } return(item); }