Beispiel #1
0
        /// <summary>
        /// Creates a new list in reverse order with the data of current list.
        /// List must have atleast one element to perform reverse-clone operation.
        /// </summary>
        /// <returns>Head node of the newly created list. Null if the list is empty.</returns>
        public Singly ReverseClone()
        {
            if (IsEmpty)
            {
                return(null);
            }

            var newSingly = new Singly();
            var current   = Head;

            while (current != null)
            {
                newSingly.AddFirst(current.Data);
                current = current.Next;
            }

            return(newSingly);
        }
Beispiel #2
0
        /// <summary>
        /// Checks if the list is a palindrome or not.
        /// </summary>
        /// <returns>true if the list is palindrome, false otherwise.</returns>
        public bool IsPalindrome()
        {
            if (IsEmpty)
            {
                return(false);
            }
            if (Count == 1)
            {
                return(true);
            }
            if (Count == 2 || Count == 3)
            {
                return(Head.Data == Tail.Data);
            }
            if (Head.Data != Tail.Data)
            {
                return(false);
            }

            var middleNode        = IsCountOdd ? InternalGetMiddleNode().Next : InternalGetMiddleNode();
            var reverseSecondHalf = new Singly();

            while (middleNode != null)
            {
                reverseSecondHalf.AddFirst(middleNode.Data);
                middleNode = middleNode.Next;
            }

            var reverseCurrent = reverseSecondHalf.Head;
            var actualCurrent  = Head;

            while (reverseCurrent != null)
            {
                if (reverseCurrent.Data != actualCurrent.Data)
                {
                    return(false);
                }
                reverseCurrent = reverseCurrent.Next;
                actualCurrent  = actualCurrent.Next;
            }

            return(true);
        }