예제 #1
0
        // Alternative
        public static Node <T> GetFromLast2 <T>(InterviewStuff.LinkedList.LinkedList <T> list, int n)
        {
            Node <T> slow = list.GetAt(0);
            Node <T> fast = list.GetAt(n);

            // while there's still a next node to visit
            while (fast.Next != null)
            {
                slow = slow.Next;
                fast = fast.Next;
            }

            return(slow);
        }
        public static bool IsCircular <T>(InterviewStuff.LinkedList.LinkedList <T> list)
        {
            Node <T> slow = list.GetFirst();
            Node <T> fast = list.GetFirst();

            // if either of the below while loop conditions is false, that means we DON'T have a circular linked list
            while (fast.Next != null && fast.Next.Next != null)
            {
                slow = slow.Next;
                fast = fast.Next.Next;

                if (slow == fast)
                {
                    return(true); // we have a circular linked list
                }
            }

            return(false);
        }
예제 #3
0
        public static Node <T> GetFromLast <T>(InterviewStuff.LinkedList.LinkedList <T> list, int n)
        {
            Node <T> slow = list.GetFirst();
            Node <T> fast = list.GetFirst();

            // could use a for loop as well
            while (n > 0)
            {
                fast = fast.Next;
                n--;
            }

            // while there's still a next node to visit
            while (fast.Next != null)
            {
                slow = slow.Next;
                fast = fast.Next;
            }

            return(slow);
        }