Exemple #1
0
        protected LinkedNode Get(LinkedNode node, int index)
        {
            if (node == null)
            {
                return(null);
            }
            if (index <= 0)
            {
                return(node);
            }

            return(Get(node.Next, index - 1));
        }
Exemple #2
0
        /** Append a node of value val to the last element of the linked list. */
        public void AddAtTail(int val)
        {
            var node = new LinkedNode(val);

            if (_root == null)
            {
                _root = node;
            }
            else
            {
                Get(_root, _len - 1).Next = node;
            }

            _len++;
        }
Exemple #3
0
        /** 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);
                return;
            }

            var node = new LinkedNode(val);

            if (_root == null)
            {
                _root = node;
            }
            else
            {
                LinkedNode searchNode;

                if (index + 1 > val)
                {
                    searchNode = Get(_root, _len - 1);
                }
                else
                {
                    searchNode = Get(_root, index - 1);
                }

                if (searchNode.Next == null)
                {
                    searchNode.Next = node;
                }
                else
                {
                    node.Next       = searchNode.Next;
                    searchNode.Next = node;
                }
            }

            _len++;
        }
Exemple #4
0
 public LinkedNode(int value, LinkedNode next)
 {
     Value = value;
     Next  = next;
 }