Exemplo n.º 1
0
        public static MyLinkedList <int> MakePartition(MyLinkedList <int> list, int value)
        {
            /*
             *  Write code to partition a linked list around a value x, such that all nodes less than x come
             *  before all nodes greater than or equal to x. lf x is contained within the list, the values of x only need
             *  to be after the elements less than x (see below). The partition element x can appear anywhere in the
             *  "right partition"; it does not need to appear between the left and right partitions.
             *  EXAMPLE
             *  Input: 3 -> 5 -> 8 -> 5 - > 10 -> 2 -> 1 [partition = 5)
             *  Output: 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8
             */

            MyLinkedList <int> before = new MyLinkedList <int>();
            MyLinkedList <int> after  = new MyLinkedList <int>();

            for (int i = 1; i <= list.Size; i++)
            {
                if (list[i] < value)
                {
                    before.AddNode(list[i]);
                }
                else
                {
                    after.AddNode(list[i]);
                }
            }

            before.AppendList(after);

            return(before);
        }
Exemplo n.º 2
0
        public static MyLinkedList <char> Sum(MyLinkedList <char> list1, MyLinkedList <char> list2)
        {
            /*
             * You have two numbers represented by a linked list, where each node
             * contains a single digit. The digits are stored in reverse order, such that the 1's
             * digit is at the head of the list. Write a function that adds the two numbers
             * and returns the sum as a linked list.
             *
             * Example:
             * Input: (7->1->6) + (5->9->2). That is, 617+295.
             * Output: 2->1->9. That is, 912.
             */

            MyLinkedList <char> result;

            StringBuilder n1 = new StringBuilder();
            StringBuilder n2 = new StringBuilder();
            string        sum;

            int int1, int2, size;

            size = list1.Size > list2.Size ? list1.Size : list2.Size;

            for (int i = size; i >= 1; i--)
            {
                if (!ReferenceEquals(list1[i], null))
                {
                    n1.Append(list1[i]);
                }

                if (!ReferenceEquals(list2[i], null))
                {
                    n2.Append(list2[i]);
                }
            }

            int1 = int.Parse(n1.ToString());
            int2 = int.Parse(n2.ToString());

            sum = (int1 + int2).ToString();

            result = new MyLinkedList <char>();

            for (int i = sum.Length - 1; i >= 0; i--)
            {
                result.AddNode(sum[i]);
            }

            return(result);
        }