// Add a node in-between 2 other nodes public void Insert(int index, T value) // O(n) { // If index out of range if (index > length) { throw new IndexOutOfRangeException("Index " + index + " out of range"); } else if (index == 1) // If index == 1, prepend { Prepend(value); return; } //Else // Start from the first node Node <T> current = this.head; int counter = 1; // Find the one selected while (current.Next != null && counter + 1 < index) { current = current.Next; counter++; } Node <T> restOfChain = current.Next; // Save the rest of the chain current.SetNextNode(new Node <T>(value)); // Create a new node as the next // Attach the rest of the chain to it current = current.Next; current.SetNextNode(restOfChain); this.length++; // Add 1 to Length }
public void InsertSorted(int val) { Node nodeToAdd = new Node(val); // if headNode is a smaller value than val, it remains the head. if (headNode.GetValue() < val) { // Check where this new node will be inserted Node currentNode = headNode; if (headNode.GetNextNode() != null) { while (currentNode.GetNextNode() != null) { // Check if we insert after currentNode if (nodeToAdd.GetValue() > currentNode.GetValue()) { // Check if nextNode is higher if (nodeToAdd.GetValue() > currentNode.GetNextNode().GetValue()) { currentNode = currentNode.GetNextNode(); continue; } // The new node is not higher so insert after our currentNode // Set the remaining portion of our list into the node to add nodeToAdd.SetNextNode(currentNode.GetNextNode()); // Add the new node to the list currentNode.SetNextNode(nodeToAdd); sizeOfList++; return; } currentNode = currentNode.GetNextNode(); } // We've made it to the end of our list! Add the node at the end currentNode.SetNextNode(nodeToAdd); sizeOfList++; } // there is no next node on the head, so we can just add it else { headNode.SetNextNode(nodeToAdd); sizeOfList++; } } // headNode is larger than value, it is no longer the head else { nodeToAdd.SetNextNode(headNode); headNode = nodeToAdd; sizeOfList++; } }
// Remove node at selected index public void RemoveAt(int index) // O(n) { // If index out of range if (index > length) { throw new IndexOutOfRangeException("Index " + index + " out of range"); } else if (index == 1) // If index == 1, prepend { this.head = this.head.Next; this.length--; // Subtract 1 from length return; } //Else // Start from the first node Node <T> current = this.head; int counter = 1; // Find the one selected while (current.Next != null && counter + 1 < index) { current = current.Next; counter++; } current.SetNextNode(current.Next.Next); this.length--; // Subtract 1 from length }
// Add a node and make it head of the chain public void Prepend(T value) // O(1) { Node <T> newFirst = new Node <T>(value); // Create a new node // Make it the first of the chain newFirst.SetNextNode(this.head); this.head = newFirst; this.length++; // Add 1 to Length }