/** Append a node of value val to the last element of the linked list. */ public void AddAtTail(int val) { MyLinkedNode node = new MyLinkedNode { Value = val }; node.Next = _tail; node.Prev = _tail.Prev; _tail.Prev.Next = node; _tail.Prev = node; _count++; }
/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ public void AddAtHead(int val) { MyLinkedNode node = new MyLinkedNode { Value = val }; node.Next = _head.Next; node.Prev = _head; _head.Next.Prev = node; _head.Next = node; _count++; }
/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */ public void AddAtIndex(int index, int val) { if (index <= 0) { AddAtHead(val); } else if (index == _count) { AddAtTail(val); } else if (index < _count) { var p = GetAtIndex(index - 1); var p2 = p.Next; MyLinkedNode node = new MyLinkedNode { Value = val }; p.Next = node; node.Prev = p; node.Next = p2; p2.Prev = node; _count++; } }