Esempio n. 1
0
        public static ListNode GetKthLastNodeOfTheList(ListNode linkedList, int k)
        {
            int currentNodeIndex = 0;

            // Store list head pointer
            ListNode kthNode = linkedList;

            // Corner case
            if (linkedList == null) {
                return null;
            }

            // Skip first k nodes
            while ((currentNodeIndex < k) && (linkedList != null)) {
                linkedList = linkedList.GetNextNode();
                currentNodeIndex ++;
            }

            // No more nodes left in the list
            if (linkedList == null) {
                return null;
            }

            // Continue to iterate both pointers to the end of the list
            while (linkedList != null) {
                kthNode = kthNode.GetNextNode ();
                linkedList = linkedList.GetNextNode ();
            }

            return kthNode;
        }
Esempio n. 2
0
        public static ListNode GetKthLastNodeOfTheList(ListNode linkedList, int k)
        {
            int currentNodeIndex = 0;

            // Store list head pointer
            ListNode kthNode = linkedList;

            // Corner case
            if (linkedList == null)
            {
                return(null);
            }

            // Skip first k nodes
            while ((currentNodeIndex < k) && (linkedList != null))
            {
                linkedList = linkedList.GetNextNode();
                currentNodeIndex++;
            }

            // No more nodes left in the list
            if (linkedList == null)
            {
                return(null);
            }

            // Continue to iterate both pointers to the end of the list
            while (linkedList != null)
            {
                kthNode    = kthNode.GetNextNode();
                linkedList = linkedList.GetNextNode();
            }

            return(kthNode);
        }
Esempio n. 3
0
        public void Print()
        {
            ListNode currentNode = this;

            while (currentNode != null)
            {
                Console.Write(currentNode.data + "->");

                currentNode = currentNode.GetNextNode();
            }

            Console.Write("null\n");
        }