/// <summary> /// /// </summary> /// <param name="posIndex"></param> /// <param name="errorMessage"></param> /// <returns></returns> public bool DeleteNode(uint posIndex, out string errorMessage) { errorMessage = ""; try { if (Head == null) { errorMessage = "No node to delete"; return(true); } //delete Head node; if (posIndex == 0) { var temp = Head; Head = Head.Next; } else { int count = 0; var head = Head; while (head.Next != null && count < posIndex - 1) { count++; head = head.Next; } var temp = head.Next.Next; head.Next = temp; } return(true); }catch (Exception ex) { errorMessage = "Error occurred while deleting node"; return(false); } }
/// <summary> /// Adding new node to the single linked list. /// </summary> /// <param name="node">Node to be added to the linked list</param> /// <param name="posIndex">If inserted as head, use 0, else the position of the Linked list</param> /// <param name="errorMessage">Placeholder for error message</param> /// <returns></returns> public bool AddNewNode(SingleLinkedListNode <T> node, uint posIndex, out string errorMessage) { errorMessage = ""; try { if (node == null) { errorMessage = "Node is not initialized with data"; return(false); } if (posIndex == 0) { if (Head == null) { Head = node; return(true); } else { node.Next = Head; Head = node; } return(true); } else { int count = 0; var head = Head; while (head.Next != null && count < posIndex - 1) { count++; head = head.Next; } //Adding node at the tail. if (head.Next == null) { head.Next = node; node.Next = null; } else { var temp = head.Next; head.Next = node; node.Next = temp; } return(true); } }catch (Exception ex) { return(false); } }
public bool DeleteNode(uint posIndex, out string errorMessage) { errorMessage = ""; try { if (posIndex == 0) { var temp = Head; while (temp.Next != Head) { temp = temp.Next; } temp.Next = Head.Next; Head = temp; } else { int count = 0; var temp = Head; while (temp.Next != Head && count < posIndex - 1) { temp = temp.Next; count++; } if (temp.Next == Head) { temp.Next = Head.Next; Head = temp; } else { temp.Next = temp.Next.Next; } } return(true); }catch (Exception ex) { errorMessage = ex.ToString(); return(false); } }
public bool AddNewNode(SingleLinkedListNode <T> node, uint posIndex, out string errorMessage) { errorMessage = ""; if (node == null) { errorMessage = "Node can't be null"; return(false); } try { if (posIndex == 0) { if (Head == null) { Head = node; node.Next = Head; } else { var temp = Head; //Traverse to the end of Head, to get Head's previous node while (temp.Next != Head) { temp = temp.Next; } temp.Next = node; node.Next = Head; Head = node; } } else { int count = 0; var temp = Head; while (temp.Next != Head && count < posIndex - 1) { temp = temp.Next; count++; } //Updating the head node if (temp.Next == Head) { temp.Next = node; node.Next = Head; Head = node; } else { node.Next = temp.Next; temp.Next = node; } } return(true); }catch (Exception ex) { errorMessage = ex.ToString(); return(false); } }