//We are adding before the head to implement as a stack (Each new node added becomes the head) //O(1) time complexity public void Push(object x) { Node n = new Node(x); n.Next = head; this.head = n; Count++; }
//Worst case time complexity is O(n) if insertion is at end of list //Passing a 1 for position adds object at head (it becomes first in the stack) //passing the stack (count + 1) for position adds the inserted node at the end //of the linked list stack, 0 is considered an invalid index public void Insert(int position, object x) { if ((position < 1) || (position > Count + 1)) throw new IndexOutOfRangeException("Invalid index"); if (position == 1) { this.Push(x); return; } //Set two pointer nodes to first and second position Node lag = head; Node lead = head.Next; Node toInsert = new Node(x); //Set the pointers to the nodes immediately before and after the inserted node for (int i = 2; i < position; i++) { lag = lag.Next; lead = lead.Next; } //Make the insertion lag.Next = toInsert; toInsert.Next = lead; }
//Delete middle node in a linked list //This method will delete any passed node except for the last node //Attempting to delete the last node in this manner will not work public void DeleteMiddle(Node x) { if (x.Next == null) return; //Copy data from next node to passed node x.Data = x.Next.Data; //Set Next pointer to node after copied data x.Next = x.Next.Next; }
//O(1) time complexity public object Pop() { //This is how the C# Stack implementation in System.Collections handles popping an empty stack if (head == null) throw new InvalidOperationException("Stack empty"); object result = head.Data; this.head = head.Next; return result; }
//Clears the Stack, resets the count public void Clear() { head = null; Count = 0; }
public LinkedListStack() { head = null; }