Example #1
0
        static int Count(ListNode head)
        {
            int count = 0;
            while (head != null)
            {
                count++;
                head = head.Next;
            }

            return count;
        }
Example #2
0
        static ListNode BuildList(int[] array)
        {
            ListNode head = new ListNode() { Value = array[0] };
            var current = head;

            for (int i = 1; i < array.Length; i++)
            {
                current.Next = new ListNode() { Value = array[i] };
                current = current.Next;
            }

            return head;
        }
Example #3
0
        public void Add(int x)
        {
            count++;

            if (head == null)
            {
                head = new ListNode(x);
                tail = head;
                return;
            }

            tail.next = new ListNode(x);
            tail = tail.next;
        }
Example #4
0
        private static TreeNode DoConvert(ref ListNode head, int n)
        {
            if (n <= 0)
            {
                return null;
            }

            TreeNode left = DoConvert(ref head, n / 2);

            TreeNode root = new TreeNode() { Value = head.Value, Left = left };

            head = head.Next;

            root.Right = DoConvert(ref head, n - n / 2 - 1);

            return root;
        }
Example #5
0
        private void ShuffleRecursive(ListNode head, int size)
        {
            if (size <= 1)
            {
                return;
            }

            int halfSize = size / 2;

            ListNode right = head;

            for (int i = 0; i < halfSize; i++)
            {
                right = right.next;
            }

            ShuffleRecursive(head, halfSize);
            ShuffleRecursive(right, size - halfSize);

            if (ShouldFlip() || true)
            {
                Flip(head, halfSize, right, size - halfSize);
            }
        }
Example #6
0
        private void Flip(ListNode left, int leftSize, ListNode right, int rightSize)
        {
            ListNode leftTail = left;
            ListNode rightTail = right;

            //find last element on the left
            for (int i = 1; i < leftSize; i++)
            {
                leftTail = leftTail.next;
            }

            //find last element on the right
            for (int i = 1; i < rightSize; i++)
            {
                rightTail = rightTail.next;
            }

            ListNode temp = rightTail.next;

            //last element of right points to first element of the left
            rightTail.next = left;

            //last element of left, points to right's old tail
            leftTail.next = temp;
        }
Example #7
0
        static TreeNode Convert(ListNode head)
        {
            int n = Count(head);

            return DoConvert(ref head, n);
        }