private LinkedListNode NthToLast(LinkedListNode head, int n)
        {
            var p1 = head;
            var p2 = head;

            if (n <= 0) return null;

            // Move p2 n nodes into the list.  Keep n1 in the same position.
            for (var i = 0; i < n - 1; i++)
            {
                if (p2 == null)
                {
                    return null; // Error: list is too small.
                }

                p2 = p2.Next;
            }
            if (p2 == null)
            { // Another error check.
                return null;
            }

            // Move them at the same pace.  When p2 hits the end,
            // p1 will be at the right element.
            while (p2.Next != null)
            {
                p1 = p1.Next;
                p2 = p2.Next;
            }

            return p1;
        }
Esempio n. 2
0
File: Q02_6.cs Progetto: 0x0all/ctci
        LinkedListNode FindBeginning(LinkedListNode head)
        {
            LinkedListNode slow = head;
            LinkedListNode fast = head;

            // Find meeting point
            while (fast != null && fast.Next != null)
            {
                slow = slow.Next;
                fast = fast.Next.Next;
                if (slow == fast)
                {
                    break;
                }
            }

            // Error check - there is no meeting point, and therefore no loop
            if (fast == null || fast.Next == null)
            {
                return null;
            }

            /* Move slow to Head. Keep fast at Meeting Point. Each are k steps
            /* from the Loop Start. If they move at the same pace, they must
             * meet at Loop Start. */
            slow = head;
            while (slow != fast)
            {
                slow = slow.Next;
                fast = fast.Next;
            }

            // Both now point to the start of the loop.
            return fast;
        }
Esempio n. 3
0
        void DeleteDupsB(LinkedListNode head)
        {
            if (head == null) return;

            var current = head;

            while (current != null)
            {
                /* Remove all future nodes that have the same value */
                var runner = current;

                while (runner.Next != null)
                {
                    Tap(0);

                    if (runner.Next.Data == current.Data)
                    {
                        runner.Next = runner.Next.Next;
                    }
                    else
                    {
                        runner = runner.Next;
                    }
                }
                current = current.Next;
            }
        }
        public static LinkedListNode findIntersection(LinkedListNode list1, LinkedListNode list2)
        {
            if (list1 == null || list2 == null) return null;

            /* Get tail and sizes. */
            Result result1 = getTailAndSize(list1);
            Result result2 = getTailAndSize(list2);

            /* If different tail nodes, then there's no intersection. */
            if (result1.tail != result2.tail)
            {
                return null;
            }

            /* Set pointers to the start of each linked list. */
            LinkedListNode shorter = result1.size < result2.size ? list1 : list2;
            LinkedListNode longer = result1.size < result2.size ? list2 : list1;

            /* Advance the pointer for the longer linked list by the difference in lengths. */
            longer = getKthNode(longer, Math.Abs(result1.size - result2.size));

            /* Move both pointers until you have a collision. */
            while (shorter != longer)
            {
                shorter = shorter.Next;
                longer = longer.Next;
            }

            /* Return either one. */
            return longer;
        }
Esempio n. 5
0
        public void Run()
        {
            /* Create linked list */
            int[] vals = {1, 3, 7, 5, 2, 9, 4};
            var head = new LinkedListNode(vals[0], null, null);
            var current = head;

            for (var i = 1; i < vals.Length; i++)
            {
                current = new LinkedListNode(vals[i], null, current);
            }
            Console.WriteLine(head.PrintForward());

            var head2 = head.Clone();
            var head3 = head.Clone();
            var head4 = head.Clone();

            /* Partition */
            var h = Partition(head, 5);
            var h2 = Partition2(head2, 5);
            var h3 = Partition3(head3, 5);
            var h4 = Partition4(head4, 5);

            /* Print Result */
            Console.WriteLine(h.PrintForward());
            Console.WriteLine(h2.PrintForward());
            Console.WriteLine(h3.PrintForward());
            Console.WriteLine(h4.PrintForward());
        }
        public void Run()
        {
            const int length = 10;
            var nodes = new LinkedListNode[length];

            for (var i = 0; i < length; i++)
            {
                nodes[i] = new LinkedListNode(i >= length / 2 ? length - i - 1 : i, null, null);
            }

            for (var i = 0; i < length; i++)
            {
                if (i < length - 1)
                {
                    nodes[i].SetNext(nodes[i + 1]);
                }

                if (i > 0)
                {
                    nodes[i].SetPrevious(nodes[i - 1]);
                }
            }
            // nodes[length - 2].data = 9; // Uncomment to ruin palindrome

            var head = nodes[0];
            Console.WriteLine(head.PrintForward());
            Console.WriteLine(IsPalindrome(head));
            Console.WriteLine(IsPalindrome2(head));
        }
Esempio n. 7
0
        public void Run()
        {
            var first = new LinkedListNode(0, null, null);
            var originalList = first;
            var second = first;

            for (var i = 1; i < 8; i++)
            {
                second = new LinkedListNode(i % 2, null, null);
                first.SetNext(second);
                second.SetPrevious(first);
                first = second;
            }

            var list1 = originalList.Clone();
            var list2 = originalList.Clone();
            var list3 = originalList.Clone();

            DeleteDupsA(list1);
            DeleteDupsB(list2);
            DeleteDupsC(list3);

            Console.WriteLine(originalList.PrintForward());
            Console.WriteLine(list1.PrintForward());
            Console.WriteLine(list1.PrintForward());
            Console.WriteLine(list1.PrintForward());

            Console.WriteLine(_tapB);
            Console.WriteLine(_tapC);
        }
Esempio n. 8
0
File: Q02_7.cs Progetto: 0x0all/ctci
 Result IsPalindromeRecurse(LinkedListNode head, int length)
 {
     if (head == null || length == 0)
     {
         return new Result(null, true);
     }
     else if (length == 1)
     {
         return new Result(head.Next, true);
     }
     else if (length == 2)
     {
         return new Result(head.Next.Next, head.Data == head.Next.Data);
     }
     Result res = IsPalindromeRecurse(head.Next, length - 2);
     if (!res.result || res.node == null)
     {
         return res; // Only "result" member is actually used in the call stack.
     }
     else
     {
         res.result = head.Data == res.node.Data;
         res.node = res.node.Next;
         return res;
     }
 }
        private LinkedListNode AddLists(LinkedListNode list1, LinkedListNode list2, int carry)
        {
            if (list1 == null && list2 == null && carry == 0)
            {
                return null;
            }

            var result = new LinkedListNode();
            var value = carry;

            if (list1 != null)
            {
                value += list1.Data;
            }
            if (list2 != null)
            {
                value += list2.Data;
            }

            result.Data = value % 10;

            if (list1 != null || list2 != null)
            {
                var more = AddLists(list1 == null ? null : list1.Next,
                                               list2 == null ? null : list2.Next,
                                               value >= 10 ? 1 : 0);
                result.SetNext(more);
            }

            return result;
        }
Esempio n. 10
0
File: Q02_7.cs Progetto: 0x0all/ctci
	    bool IsPalindrome2(LinkedListNode head) {
		    LinkedListNode fast = head;
		    LinkedListNode slow = head;
		
		    Stack<int> stack = new Stack<int>();
		
		    while (fast != null && fast.Next != null) {
                stack.Push(slow.Data);
			    slow = slow.Next;
			    fast = fast.Next.Next;			
		    }
		
		    /* Has odd number of elements, so skip the middle */
		    if (fast != null) { 
			    slow = slow.Next;
		    }
		
		    while (slow != null) {
			    int top = stack.Pop();
                Console.WriteLine(slow.Data + " " + top);
			    if (top != slow.Data) {
				    return false;
			    }
			    slow = slow.Next;
		    }
		    return true;
	    }
        public void Run()
        {
            const int listLength = 10;
            const int k = 3;

            // Create linked list
            var nodes = new LinkedListNode[listLength];

            for (var i = 1; i <= listLength; i++)
            {
                nodes[i - 1] = new LinkedListNode(i, null, i - 1 > 0 ? nodes[i - 2] : null);
                Console.Write("{0} -> ", nodes[i - 1].Data);
            }
            Console.WriteLine();

            // Create loop;
            nodes[listLength - 1].Next = nodes[listLength - k - 1];
            Console.WriteLine("{0} -> {1}", nodes[listLength - 1].Data, nodes[listLength - k - 1].Data);

            var loop = FindBeginning(nodes[0]);

            if (loop == null)
            {
                Console.WriteLine("No Cycle.");
            }
            else
            {
                Console.WriteLine(loop.Data);
            }
        }
Esempio n. 12
0
File: Q02_5.cs Progetto: 0x0all/ctci
        LinkedListNode AddLists(LinkedListNode l1, LinkedListNode l2, int carry)
        {
            if (l1 == null && l2 == null && carry == 0)
            {
                return null;
            }

            LinkedListNode result = new LinkedListNode();
            int value = carry;
            if (l1 != null)
            {
                value += l1.Data;
            }
            if (l2 != null)
            {
                value += l2.Data;
            }
            result.Data = value % 10;
            if (l1 != null || l2 != null)
            {
                LinkedListNode more = AddLists(l1 == null ? null : l1.Next,
                                               l2 == null ? null : l2.Next,
                                               value >= 10 ? 1 : 0);
                result.SetNext(more);
            }
            return result;
        }
 public void SetPrevious(LinkedListNode p)
 {
     Prev = p;
     if (p != null && p.Next != this)
     {
         p.SetNext(this);
     }
 }
Esempio n. 14
0
File: Q02_2.cs Progetto: 0x0all/ctci
 LinkedListNode NthToLastR3(LinkedListNode head, int k)
 {
     Result res = NthToLastR3Helper(head, k);
     if (res != null)
     {
         return res.Node;
     }
     return null;
 }
Esempio n. 15
0
File: Q02_5.cs Progetto: 0x0all/ctci
 int LinkedListToInt(LinkedListNode node)
 {
     int value = 0;
     if (node.Next != null)
     {
         value = 10 * LinkedListToInt(node.Next);
     }
     return value + node.Data;
 }
        public void Run()
        {
            #region First Part

            {
                var lA1 = new LinkedListNode(9, null, null);
                var lA2 = new LinkedListNode(9, null, lA1);
                var lA3 = new LinkedListNode(9, null, lA2);

                var lB1 = new LinkedListNode(1, null, null);
                var lB2 = new LinkedListNode(0, null, lB1);
                var lB3 = new LinkedListNode(0, null, lB2);

                var list3 = AddLists(lA1, lB1, 0);

                Console.WriteLine("  " + lA1.PrintForward());
                Console.WriteLine("+ " + lB1.PrintForward());
                Console.WriteLine("= " + list3.PrintForward());

                var l1 = LinkedListToInt(lA1);
                var l2 = LinkedListToInt(lB1);
                var l3 = LinkedListToInt(list3);

                Console.Write(l1 + " + " + l2 + " = " + l3 + "\n");
                Console.WriteLine(l1 + " + " + l2 + " = " + (l1 + l2));
            }

            #endregion First Part

            #region Followup

            {
                var lA1 = new LinkedListNode(3, null, null);
                var lA2 = new LinkedListNode(1, null, lA1);
                //LinkedListNode lA3 = new LinkedListNode(5, null, lA2);

                var lB1 = new LinkedListNode(5, null, null);
                var lB2 = new LinkedListNode(9, null, lB1);
                var lB3 = new LinkedListNode(1, null, lB2);

                var list3 = AddLists2(lA1, lB1);

                Console.WriteLine("  " + lA1.PrintForward());
                Console.WriteLine("+ " + lB1.PrintForward());
                Console.WriteLine("= " + list3.PrintForward());

                var l1 = linkedListToInt(lA1);
                var l2 = linkedListToInt(lB1);
                var l3 = linkedListToInt(list3);

                Console.Write(l1 + " + " + l2 + " = " + l3 + "\n");
                Console.WriteLine(l1 + " + " + l2 + " = " + (l1 + l2));
            }

            #endregion Followup
        }
 public static LinkedListNode getKthNode(LinkedListNode head, int k)
 {
     LinkedListNode current = head;
     while (k > 0 && current != null)
     {
         current = current.Next;
         k--;
     }
     return current;
 }
 public LinkedListNode Clone()
 {
     LinkedListNode next2 = null;
     if (Next != null)
     {
         next2 = Next.Clone();
     }
     LinkedListNode head2 = new LinkedListNode(Data, next2, null);
     return head2;
 }
 public static LinkedListNode CreateLinkedListFromArray(int[] vals)
 {
     LinkedListNode head = new LinkedListNode(vals[0], null, null);
     LinkedListNode current = head;
     for (int i = 1; i < vals.Length; i++)
     {
         current = new LinkedListNode(vals[i], null, current);
     }
     return head;
 }
Esempio n. 20
0
	    public static LinkedListNode LinkedListWithValue(int N, int value)
        {
		    LinkedListNode root = new LinkedListNode(value, null, null);
		    LinkedListNode prev = root;
		    for (int i = 1; i < N; i++) {
			    LinkedListNode next = new LinkedListNode(value, null, null);
			    prev.SetNext(next);
			    prev = next;
		    }
		    return root;
	    }	
Esempio n. 21
0
File: Q02_2.cs Progetto: 0x0all/ctci
        int NthToLastR1(LinkedListNode head, int n)
        {
		    if (n == 0 || head == null) {
			    return 0;
		    }
		    int k = NthToLastR1(head.Next, n) + 1;
		    if (k == n) {
			    Console.WriteLine(n + "th to last node is " + head.Data);
		    }
		    return k;
	    }
Esempio n. 22
0
File: Q02_3.cs Progetto: 0x0all/ctci
 bool DeleteNode(LinkedListNode n)
 {
     if (n == null || n.Next == null)
     {
         return false; // Failure
     }
     LinkedListNode next = n.Next;
     n.Data = next.Data;
     n.Next = next.Next;
     return true;
 }
Esempio n. 23
0
File: Q02_5.cs Progetto: 0x0all/ctci
 int Length(LinkedListNode l)
 {
     if (l == null)
     {
         return 0;
     }
     else
     {
         return 1 + Length(l.Next);
     }
 }
Esempio n. 24
0
	    public static LinkedListNode RandomLinkedList(int N, int min, int max)
        {
		    LinkedListNode root = new LinkedListNode(RandomIntInRange(min, max), null, null);
		    LinkedListNode prev = root;
		    for (int i = 1; i < N; i++) {
			    int data = RandomIntInRange(min, max);
			    LinkedListNode next = new LinkedListNode(data, null, null);
			    prev.SetNext(next);
			    prev = next;
		    }
		    return root;
	    }
Esempio n. 25
0
File: Q02_7.cs Progetto: 0x0all/ctci
 bool IsPalindrome(LinkedListNode head)
 {
     int size = 0;
     LinkedListNode n = head;
     while (n != null)
     {
         size++;
         n = n.Next;
     }
     Result p = IsPalindromeRecurse(head, size);
     return p.result;
 }
 public void SetNext(LinkedListNode n)
 {
     Next = n;
     if (this == Last)
     {
         Last = n;
     }
     if (n != null && n.Prev != this)
     {
         n.SetPrevious(this);
     }
 }
Esempio n. 27
0
        LinkedListNode Partition(LinkedListNode node, int pivot)
        {
            LinkedListNode beforeStart = null;
            LinkedListNode beforeEnd = null;
            LinkedListNode afterStart = null;
            LinkedListNode afterEnd = null;

            /* Partition list */
            while (node != null)
            {
                var next = node.Next;
                node.Next = null;

                if (node.Data < pivot)
                {
                    if (beforeStart == null)
                    {
                        beforeStart = node;
                        beforeEnd = beforeStart;
                    }
                    else
                    {
                        beforeEnd.Next = node;
                        beforeEnd = node;
                    }
                }
                else
                {
                    if (afterStart == null)
                    {
                        afterStart = node;
                        afterEnd = afterStart;
                    }
                    else
                    {
                        afterEnd.Next = node;
                        afterEnd = node;
                    }
                }
                node = next;
            }

            /* Merge before list and after list */
            if (beforeStart == null)
            {
                return afterStart;
            }

            beforeEnd.Next = afterStart;

            return beforeStart;
        }
Esempio n. 28
0
File: Q02_5.cs Progetto: 0x0all/ctci
 PartialSum AddListsHelper(LinkedListNode l1, LinkedListNode l2)
 {
     if (l1 == null && l2 == null)
     {
         return new PartialSum();
     }
     PartialSum sum = AddListsHelper(l1.Next, l2.Next);
     int val = sum.carry + l1.Data + l2.Data;
     LinkedListNode full_result = insertBefore(sum.sum, val % 10);
     sum.sum = full_result;
     sum.carry = val / 10;
     return sum;
 }
        public static Result getTailAndSize(LinkedListNode list)
        {
            if (list == null) return null;

            int size = 1;
            LinkedListNode current = list;
            while (current.Next != null)
            {
                size++;
                current = current.Next;
            }
            return new Result(current, size);
        }
        private bool DeleteNode(LinkedListNode node)
        {
            if (node == null || node.Next == null)
            {
                return false; // Failure
            }

            var next = node.Next;
            node.Data = next.Data;
            node.Next = next.Next;

            return true;
        }