private int listlen = 0; //length of the linked list #endregion Fields #region Methods //Add a node to the linked list; public linkedList_return create_node(int key) { //create the new node default_node newNode = new default_node(); newNode.key = key; newNode.next = null; //check to see if the linked list is empty if(head == null) { head = newNode; listlen++; return linkedList_return.SUCCESS; } //else, add the linked list in order by key value default_node prev = head; default_node current = head; if(newNode.key < head.key) //new node is head node { newNode.next = head; head = newNode; listlen++; return linkedList_return.SUCCESS; } while (current.key <= newNode.key) { //if we find a node with the same value, return an error if(current.key == key) { newNode = null; return linkedList_return.CREATE_FAILED_DUPLICATE_KEY; } prev = current; current = current.next; //break if the end of the list is reached if (current == null) { break; } } //and insert newNode prev.next = newNode; newNode.next = current; listlen++; return linkedList_return.SUCCESS; }
//Delete a node from the linked list public linkedList_return delete_node(int key) { default_node prev = head; default_node current = head; //check to see if we need to delete the head node if(head.key == key) { head = head.next; listlen--; return linkedList_return.SUCCESS; } //search through the linked list until the node is found while(current != null) { //if found, delete the node if(current.key == key) { prev.next = current.next; current = null; listlen--; return linkedList_return.SUCCESS; } //else, move to the next node prev = current; current = current.next; } //return error if the node was not found return linkedList_return.DELETE_FAILED_KEY_NOT_FOUND; }